拆分pandas数据帧的所有列表列

时间:2018-03-07 09:49:35

标签: python pandas dataframe

我有一个dataframe有很多列

df=
                                                    c1\
2015-01-01  [50.4750711276, 50.4750711276, 50.4750711276]   
2015-01-02  [50.5349107929, 50.5349107929, 50.5349107929]     

                                                   c2
2015-01-01  [33.5322374641, 33.5322374641, 33.5322374641]  
2015-01-02  [33.4770757092, 33.4770757092, 33.4770757092]  

我想将每列拆分为包含列表中单个元素的列。喜欢(对于c1)

          0          1          2
0  50.475071  50.475071  50.475071
1  50.534911  50.534911  50.534911

我能做到

pd.DataFrame(df.c1.values.tolist()).add_prefix('code_')

但是如何同时为所有列执行此操作并且能够根据列的名称添加前缀?

1 个答案:

答案 0 :(得分:3)

list comprehensionconcat

一起使用
comp = [pd.DataFrame(df[x].values.tolist(), index=df.index).add_suffix('_code_' + x) 
         for x in df.columns]
df = pd.concat(comp, axis=1)
print (df)
            0_code_c1  1_code_c1  2_code_c1  0_code_c2  1_code_c2  2_code_c2
2015-01-01  50.475071  50.475071  50.475071  33.532237  33.532237  33.532237
2015-01-02  50.534911  50.534911  50.534911  33.477076  33.477076  33.477076

编辑:

names = list('ABC')
comp = [pd.DataFrame(df[x].values.tolist(), index=df.index, columns=names).add_suffix('_' + x)
         for i, x in enumerate(df.columns)]
df = pd.concat(comp, axis=1)
print (df)
                 A_c1       B_c1       C_c1       A_c2       B_c2       C_c2
2015-01-01  50.475071  50.475071  50.475071  33.532237  33.532237  33.532237
2015-01-02  50.534911  50.534911  50.534911  33.477076  33.477076  33.477076