【问题标题】:Splitting a column of strings and counting the number of words with pandas [duplicate]拆分一列字符串并用熊猫计算单词的数量[重复]
【发布时间】:2018-06-06 19:44:29
【问题描述】:
id   string   
0    31672;0           
1    31965;0
2    0;78464
3      51462
4    31931;0

嗨,我有那张桌子。我想用';'分割字符串表,并将其存储到新列中。最后一列应该是这样的

 id   string   word_count
0    31672;0    2       
1    31965;0    2
2    0;78464    2
3      51462    1
4    31931;0    2

如果有人知道如何用 python 做到这一点,那就太好了。

【问题讨论】:

  • 您在寻找df['string'].str.count(';') + 1吗?
  • 您好,感谢您的回复。但这不是我要找的。如果“string”列值为空字符串,该代码将向“word_count”列写入“1”:)

标签: python string pandas dataframe


【解决方案1】:

选项 1
基本解决方案使用str.split + str.len -

df['word_count'] = df['string'].str.split(';').str.len()
df

     string  word_count
id                     
0   31672;0           2
1   31965;0           2
2   0;78464           2
3     51462           1
4   31931;0           2

选项 2
str.count 的聪明(高效,占用空间更少)解决方案 -

df['word_count'] = df['string'].str.count(';') + 1
df

     string  word_count
id                     
0   31672;0           2
1   31965;0           2
2   0;78464           2
3     51462           1
4   31931;0           2

警告 - 即使对于空字符串,这也会将字数归为 1(在这种情况下,请坚持使用选项 1)。


如果您希望每个单词占据一个新列,有一种使用tolist 的快速简单的方法,将拆分加载到新数据帧中,然后使用concat 将新数据帧与原始数据帧连接 -

v = pd.DataFrame(df['string'].str.split(';').tolist())\
        .rename(columns=lambda x: x + 1)\
        .add_prefix('string_')

pd.concat([df, v], 1)

     string  word_count string_1 string_2
id                                       
0   31672;0           2    31672        0
1   31965;0           2    31965        0
2   0;78464           2        0    78464
3     51462           1    51462     None
4   31931;0           2    31931        0

【讨论】:

  • @AldemuroMandalamuriAbdulHar 谢谢,我应该假设每个聪明的解决方案都有自己的一套警告。
  • 完成了,它不再是灰色的了:D
  • @AldemuroMandalamuriAbdulHar 干杯,节日快乐 :-)
猜你喜欢
  • 2018-07-08
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 2018-02-11
相关资源
最近更新 更多