Python 拆分一列字符串并使用pandas计算字数

Python 拆分一列字符串并使用pandas计算字数,python,string,pandas,dataframe,Python,String,Pandas,Dataframe,嗨,我有那张桌子。我想用“;”来拆分字符串表,并将其存储到新列中。最后一列应该是这样的 id string 0 31672;0 1 31965;0 2 0;78464 3 51462 4 31931;0 如果有人知道如何使用python,那就太好了。选项1 使用str.split+str.len- id string word_count 0 31672;0 2 1 31965;0

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

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

如果有人知道如何使用python,那就太好了。

选项1
使用
str.split
+
str.len
-

 id   string   word_count
0    31672;0    2       
1    31965;0    2
2    0;78464    2
3      51462    1
4    31931;0    2
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
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

选项2
使用
str.count
-

 id   string   word_count
0    31672;0    2       
1    31965;0    2
2    0;78464    2
3      51462    1
4    31931;0    2
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
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
将新数据帧与原始数据帧连接起来,这是一种快速而简单的方法

 id   string   word_count
0    31672;0    2       
1    31965;0    2
2    0;78464    2
3      51462    1
4    31931;0    2
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
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

您正在寻找
df['string'].str.count(“;”)+1
?您好,谢谢您的回复。但这不是我想要的。如果“string”列的值是空字符串,那么代码会将“1”写入“word_count”列:)@AldemuroMandalamuriAbdulHar谢谢,我应该假设每个聪明的解决方案都有自己的一套警告。完成后,它不再是灰色的:D@AldemuroMandalamuriAbdulHar干杯,节日快乐:-)