我正在try 拆分一列,并将最后一个"u"之后的部分存储为新列.
import pandas as pd
import numpy as np
names= ['John', 'Jane', 'Brian','Suzan', 'John']
expertise = ['primary_chat', 'follow_email', 'repeat_chat', 'primary_video_chat', 'tech_chat']
data = list(zip(names,expertise))
df = pd.DataFrame(data, columns=['Name', 'Communication'])
df
Output
Name Communication
0 John primary_chat
1 Jane follow_email
2 Brian repeat_chat
3 Suzan primary_video_chat
4 John tech_chat
通过拆分列添加新列时:
df['Platform'] = df['Communication'].str.split('_', expand=True)[1]
df
Output
Name Communication Platform
0 John primary_chat chat
1 Jane follow_email email
2 Brian repeat_chat chat
3 Suzan primary_video_chat video
4 John tech_chat chat
但问题是,[1]占据了分割的第二部分.当我们只有一个"_u"时,这不是问题,第二部分是我们需要的.但是当你有两个像第三个(Suzan)一样的"uu"时,[1]会让你得到短语"视频"而不是"邮箱",我们应该在那里有[2]索引.
我们可以动态地获取"s"的数量并使用这个值,但是,下面的代码即使输出正确的值,当我在[]中使用它作为索引值时,我会得到一个错误.
df['Communication'].str.count('_')
0 1
1 1
2 1
3 2
4 1
Name: Communication, dtype: int64
给了我正确的"x"数.但是,当我在前一行代码中使用split()并创建新列时,我得到了一个错误
df['Platform'] = df['Communication'].str.split('_', expand=True)[df['Agent Expertise'].str.count('_')]
但是我犯了一个错误..
也许我应该try 使用apply()和lambda,但我想知道是否有办法解决这个问题..