使用熊猫将字符串旋转到更多列中



我的桌子看起来如下:

import pandas as pd
d = {'col1': ['a>b>c']}
df = pd.DataFrame(data=d)
print(df)
"""
   col1
0  a>b>c
"""

我所需的输出需要这样:

d1 = {'col1': ['a>b>c'],'col11': ['a'],'col12': ['b'],'col13': ['c']}
d1 = pd.DataFrame(data=d1)
print(d1)
"""    
     col1 col11 col12 col13
 0  a>b>c     a     b     c
"""

我必须运行.split('>')方法,但后来我不知道该如何继续。有帮助吗?

您可以简单地使用str.split('>')拆分并展开DataFrame

import pandas as pd
d = {'col1': ['a>b>c'],'col2':['a>b>c']}
df = pd.DataFrame(data=d)
print(df)
col='col1'
#temp = df[col].str.split('>',expand=True).add_prefix(col)
temp = df[col].str.split('>',expand=True).rename(columns=lambda x: col + str(int(x)+1))
temp.merge(df,left_index=True,right_index=True,how='outer')

out:

     col1 col11 col12 col13
 0  a>b>c     a     b     c

如果要在多个列上进行操作,也可以服用

for col in df.columns:
    temp = df[col].str.split('>',expand=True).rename(columns=lambda x: col + str(int(x)+1))
    df = temp.merge(df,left_index=True,right_index=True,how='outer')

out:

   col21 col22 col23 col11 col12 col13  col1   col2
0   a     b      c     a     b      c   a>b>c a>b>c

使用 split

d = {'col1': ['a>b>c']}
df = pd.DataFrame(data=d)
df = pd.concat([df, df.col1.str.split('>', expand=True)], axis=1)
df.columns = ['col1', 'col11', 'col12', 'col13']
df

输出:

    col1    col11   col12   col13
0   a>b>c   a        b        c

最新更新