python - 拆分一列字符串并用 Pandas 计算单词数

标签 python string pandas dataframe

<分区>

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

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

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

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

最佳答案

选项 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

关于python - 拆分一列字符串并用 Pandas 计算单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970561/

相关文章:

python - Eventlet 和锁定

ios - 将与搜索字符串匹配的字符串的一部分加粗

python - 将对角线上方的元素移动到行的开头

python - 创建额外的记录并用 pandas 向前填充

python - 根据 pandas 中每个排序组的第一行创建一列

python - flask mysql 不为空

python - 在 Azure Cosmos DB 中插入时分区键不起作用

python - 如何修复错误消息 : 'chromedriver.exe' executable may have wrong permissions

给定索引后特殊字符的Javascript索引

java - 如何使用 Scanner 从 {int :int}? 中提取整数