使用Pandas将字符串转换为更多列

时间:2019-03-07 12:17:01

标签: python python-3.x pandas pivot

我的表格如下所示:

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('>')方法,但是我不知道如何继续。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

使用/** This is test function * @param {} param1 this is param 1 * @param {} param2 this is param 2 */ function test(param1, param2) { }

function getMethodJsDocData(){
  // The magic happens here and returns some data that contains:
  /** This is test function
   * @param  {} param1 this is param 1
   * @param  {} param2 this is param 2
   */
}

输出:

split

答案 1 :(得分:0)

您可以简单地使用str.split('>')进行拆分并展开数据框

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')

出局:

     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')

出局:

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