【问题标题】:combine or iterate pandas rows on specific columns在特定列上组合或迭代 pandas 行
【发布时间】:2018-03-02 06:35:51
【问题描述】:

我正在努力在 pandas 中逐行迭代。

我有一个数据集,其中包含两方之间的聊天对话。我想将数据集结合起来,在人 1 和人 2 之间进行逐行对话。有时人们会输入多个句子,这些句子会在数据框中显示为多条记录。

这是我回来的循环:

  1. 要合并的line_text
  2. 时间戳以最新时间更新
  3. 如果 line_by 显示同一个人输入了多行并通过他们的聊天发送
  4. 由于此数据集中有多个 id 表示人 1 和人 2 之间的每个对话记录,我希望循环由每个唯一 id 运行。

    id    timestamp line_by line_text
    1234    02:54.3 Person1 Text Line 1
    1234    03:23.8 Person2 Text Line 2
    1234    03:47.0 Person2 Text Line 3
    1234    04:46.8 Person1 Text Line 4
    1234    05:46.2 Person1 Text Line 5
    9876    06:44.5 Person2 Text Line 6
    9876    07:27.6 Person1 Text Line 7
    9876    08:17.5 Person2 Text Line 8
    9876    10:20.3 Person2 Text Line 9
    

我想看看数据改成如下:

id    timestamp line_by line_text
1234    02:54.3 Person1 Text Line 1
1234    03:47.0 Person2 Text Line 2Text Line 3
1234    05:46.2 Person1 Text Line 4Text Line 5
9876    06:44.5 Person2 Text Line 6
9876    07:27.6 Person1 Text Line 7
9876    10:20.3 Person2 Text Line 8Text Line 9

感谢任何想法。

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    您可以在连续的line_by 上使用groupby 并使用agg 聚合最新的timestamp''.join line_text

    In [1918]: (df.groupby((df.line_by != df.line_by.shift()).cumsum(), as_index=False)
                  .agg({'id': 'first', 'timestamp': 'last', 'line_by': 'first',
                       'line_text': ''.join}))
    Out[1918]:
      timestamp               line_text    id  line_by
    0   02:54.3             Text Line 1  1234  Person1
    1   03:47.0  Text Line 2Text Line 3  1234  Person2
    2   05:46.2  Text Line 4Text Line 5  1234  Person1
    3   06:44.5             Text Line 6  9876  Person2
    4   07:27.6             Text Line 7  9876  Person1
    5   10:20.3  Text Line 8Text Line 9  9876  Person2
    

    详情

    In [1919]: (df.line_by != df.line_by.shift()).cumsum()
    Out[1919]:
    0    1
    1    2
    2    2
    3    3
    4    3
    5    4
    6    5
    7    6
    8    6
    Name: line_by, dtype: int32
    
    In [1920]: df
    Out[1920]:
         id timestamp  line_by    line_text
    0  1234   02:54.3  Person1  Text Line 1
    1  1234   03:23.8  Person2  Text Line 2
    2  1234   03:47.0  Person2  Text Line 3
    3  1234   04:46.8  Person1  Text Line 4
    4  1234   05:46.2  Person1  Text Line 5
    5  9876   06:44.5  Person2  Text Line 6
    6  9876   07:27.6  Person1  Text Line 7
    7  9876   08:17.5  Person2  Text Line 8
    8  9876   10:20.3  Person2  Text Line 9
    

    【讨论】:

    • 哇。一百万谢谢。它完全符合我的要求!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2020-05-27
    • 2021-11-25
    • 1970-01-01
    • 2020-12-22
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多