首页 > 解决方案 > How to split a column into many columns where the name of this columns change

问题描述

I defined a data frame into a "function" where the name of each column in the dataframes changes continuously so I can't specify the name of this column and then split it to many columns. For example, I can't say df ['name'] and then split it into many columns. The number of columns and rows of this dataframes is not constant. I need to split any column contains more than one item to many components (columns).

For example:

This is one of the dataframes which I have:

name/one                                                name/three         

(192.26949,)                                      (435.54,436.65,87.3,5432) 

(189.4033245,)                                (45.51,56.612, 54253.543, 54.321) 

(184.4593252,)                                 (45.58,56.6412,654.876,765.66543) 

I want to convert it to:

name/one                 name/three1      name/three2     name/three3       name/three4 

192.26949                  435.54          436.65            87.3              5432 


189.4033245                45.51           56.612          54253.543          54.321 

184.4593252                45.58           56.6412          654.876          765.66543

标签: pythonpandassplitmultiple-columns

解决方案


如果所有数据都是所有行中的元组并且所有列concatDataFrame构造函数和一起使用,则解决方案DataFrame.add_prefix

df = pd.concat([pd.DataFrame(df[c].tolist()).add_prefix(c) for c in df.columns], axis=1)
print (df)
    name/one0  name/three0  name/three1  name/three2  name/three3
0  192.269490       435.54     436.6500       87.300   5432.00000
1  189.403324        45.51      56.6120    54253.543     54.32100
2  184.459325        45.58      56.6412      654.876    765.66543

如果可能的话,字符串 repr 的元组:

import ast

L = [pd.DataFrame([ast.literal_eval(y) for y in df[c]]).add_prefix(c) for c in df.columns]
df = pd.concat(L, axis=1)
print (df)
    name/one0  name/three0  name/three1  name/three2  name/three3
0  192.269490       435.54     436.6500       87.300   5432.00000
1  189.403324        45.51      56.6120    54253.543     54.32100
2  184.459325        45.58      56.6412      654.876    765.66543

推荐阅读