【问题标题】:Pandas rolling sum on string columnPandas 在字符串列上滚动总和
【发布时间】:2017-04-23 08:40:28
【问题描述】:

我正在使用 Python3 和 pandas 版本“0.19.2”。

我有一个 pandas df 如下:

chat_id    line
1          'Hi.'
1          'Hi, how are you?.'
1          'I'm well, thanks.'
2          'Is it going to rain?.'
2          'No, I don't think so.'

我想按 'chat_id' 分组,然后在 'line' 上做类似滚动求和的操作以获得以下结果:

chat_id    line                     conversation
1          'Hi.'                    'Hi.'
1          'Hi, how are you?.'      'Hi. Hi, how are you?.'
1          'I'm well, thanks.'      'Hi. Hi, how are you?. I'm well, thanks.'
2          'Is it going to rain?.'  'Is it going to rain?.'
2          'No, I don't think so.'  'Is it going to rain?. No, I don't think so.'

我相信 df.groupby('chat_id')['line'].cumsum() 只适用于数字列。

我也尝试过 df.groupby(by=['chat_id'], as_index=False)['line'].apply(list) 来获取完整对话中所有行的列表,但是我可以'不知道如何解压该列表以创建“滚动总和”风格的对话列。

【问题讨论】:

  • 有趣。 cumsum 在 Series 上调用时有效,但在 groupby 对象上调用时会引发错误。

标签: pandas text rolling-sum


【解决方案1】:

对我来说 applySeries.cumsum 一起工作,如果需要分隔符添加 space:

df['new'] = df.groupby('chat_id')['line'].apply(lambda x: (x + ' ').cumsum().str.strip())
print (df)
   chat_id                   line                                          new
0        1                    Hi.                                          Hi.
1        1      Hi, how are you?.                        Hi. Hi, how are you?.
2        1      I'm well, thanks.      Hi. Hi, how are you?. I'm well, thanks.
3        2  Is it going to rain?.                        Is it going to rain?.
4        2  No, I don't think so.  Is it going to rain?. No, I don't think so.

df['line'] = df['line'].str.strip("'")
df['new'] = df.groupby('chat_id')['line'].apply(lambda x: "'" + (x + ' ').cumsum().str.strip() + "'")
print (df)
   chat_id                   line  \
0        1                    Hi.   
1        1      Hi, how are you?.   
2        1      I'm well, thanks.   
3        2  Is it going to rain?.   
4        2  No, I don't think so.   

                                             new  
0                                          'Hi.'  
1                        'Hi. Hi, how are you?.'  
2      'Hi. Hi, how are you?. I'm well, thanks.'  
3                        'Is it going to rain?.'  
4  'Is it going to rain?. No, I don't think so.' 

【讨论】:

  • 对我来说会导致:ValueError: cannot reindex from a duplicate axis
  • 你的熊猫版本是什么? print (pd.show_versions())。因为我无法模拟你的错误。我测试了值中的重复项,索引中的重复项,并且在版本0.19.2 中都可以完美运行。
  • 对不起,你是对的。我不得不在 df 上 reset_index() 然后它工作了。
  • 如果我在对话之间有一个NaN 值(例如index 1),我如何从cumsum 中排除它?谢谢!
  • @TotoLele - 一个想法df['new'] = df.dropna(subset=['line']).groupby('chat_id')['line'].apply(lambda x: (x + ' ').cumsum().str.strip())
猜你喜欢
  • 1970-01-01
  • 2020-01-15
  • 2021-09-19
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2015-03-10
  • 2020-11-24
  • 2021-03-29
相关资源
最近更新 更多