下午好,我正在尝试将列中的文本拆分为特定格式 这是我的下表
UserId Application
1 Grey Blue::Black Orange;White:Green
2 Yellow Purple::Orange Grey;Blue Pink::Red
我希望它读取以下内容:
UserId Application
1 Grey Blue
1 White Orange
2 Yellow Purple
2 Blue Pink
基本上,我想保留给定单元格中每个字符串的每个::实例的第一个字符串。
到目前为止我的代码是
def unnesting(df, explode):
idx=df.index.repeat(df[explode[0]].str.len())
df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
df1.index=idx
return df1.join(df.drop(explode,1),how='left')
df['Application']=df.Role.str.split(';|::|').map(lambda x : x[0::2])
unnesting(df.drop('Role',1),['Application']
下面的代码读取
UserId Application
1 Grey Blue, White Orange
2 Yellow Purple, Blue Pink
请帮忙,我不知道应该在哪里使用 pandas 或 numpy 来解决这个问题!!
最佳答案
也许你可以尝试使用extractall
yourdf=df.set_index('UserId').Application.str.extractall(r'(\w+):').reset_index(level=0)
# You can adding rename(columns={0:'Application'})at the end
Out[87]:
UserId 0
match
0 1 Grey
1 1 White
0 2 Yellow
1 2 Blue
<小时/>
更新查看 unnesting ,在我们分割
并从字符串中选择我们需要的值之后,我们将它们存储到list
中,当你有一个list
类型时columns
,我建议使用 unnesting
df['LIST']=df.Application.str.split(';|::|:').map(lambda x : x[0::2])
unnesting(df.drop('Application',1),['LIST'])
Out[111]:
LIST UserId
0 Grey Blue 1
0 White 1
1 Yellow Purple 2
1 Blue Pink 2
<小时/>
我自己的定义函数
def unnesting(df, explode):
idx=df.index.repeat(df[explode[0]].str.len())
df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
df1.index=idx
return df1.join(df.drop(explode,1),how='left')
关于Python,在列中拆分多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081439/