Python,在列中分割多个字符串

时间:2019-03-09 20:04:07

标签: python pandas numpy dataframe text

下午好,我正在尝试将列中的文本拆分为特定格式 这是我的下面的桌子

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

请协助我不知道我应该在哪里使用熊猫或numpy解决此问题!

1 个答案:

答案 0 :(得分:2)

也许您可以尝试使用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,在我们split并从字符串中选择所需的值之后,将它们存储到{ {1}},当您在list中输入list时,建议使用unnesting

columns

我自己的自定义功能

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
相关问题