al1*_*991 4 python string dataframe pandas
id string
0 31672;0
1 31965;0
2 0;78464
3 51462
4 31931;0
Run Code Online (Sandbox Code Playgroud)
你好,我有那个桌子。我想通过';'拆分字符串表,并将其存储到新列中。最后一列应该是这样的
id string word_count
0 31672;0 2
1 31965;0 2
2 0;78464 2
3 51462 1
4 31931;0 2
Run Code Online (Sandbox Code Playgroud)
如果有人知道如何用 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
Run Code Online (Sandbox Code Playgroud)
选项 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
Run Code Online (Sandbox Code Playgroud)
警告 - 即使对于空字符串,这也会将字数归因于 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3280 次 |
| 最近记录: |