首页 > 解决方案 > DataFrame Column 分成多列

问题描述

柱子 柱子

如何拆分包含字符串列表的数据框列,例如

[{'1','1','1','1'},{'1','1','1','1'},{'1','1','1','1'},{'1','1','1','1'}]

在每个单元格中,分成多列数据框?

考虑到列的每个单元格中的列表长度不同!

在左上图中,我们有第一列,在右边,我们正在观察我想要制作的结果。

标签: pandasstringdataframe

解决方案


正如@Oliver Prislan 评论的那样——这是一个不寻常的结构——你的意思是别的吗?如果您的数据是这样的结构,那么您可以通过以下方式将其转换为新格式:

# assumes that your original dataframe is called `df`
# creates a new dataframe called new_df
# removes the unwanted {} and [] and ''
# then expands the columns after splitting each string on the comma
new_df = pd.DataFrame(df['Column0'].str.replace('[{}\[\]\']','').str.split(',', expand=True),
                index=df.index) 
 #renames the columns as you wanted them
new_df.rename(columns='col{}'.format, inplace=True)

如果您的值始终为数字,并且您可能希望将数据框列转换为数字数据类型:

for col in new_df.columns:
    new_df[col] = pd.to_numeric(new_df[col])

最后结果:

 col0  col1  col2  col3  col4  col5  col6  col7  col8  col9  col10  col11  col12  col13  col14  col15
0     1     1     1     1   NaN   NaN   NaN   NaN   NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN
1     1     1     1     1   1.0   1.0   1.0   1.0   1.0   1.0    1.0    1.0    1.0    1.0    1.0    1.0
2     1     1     1     1   1.0   1.0   1.0   1.0   1.0   1.0    1.0    1.0    NaN    NaN    NaN    NaN
3     1     1     1     1   NaN   NaN   NaN   NaN   NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN
4     1     1     1     1   NaN   NaN   NaN   NaN   NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN
5     1     1     1     1   1.0   1.0   1.0   1.0   NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN

推荐阅读