pandas - DataFrame Column 分成多列
问题描述
柱子
如何拆分包含字符串列表的数据框列,例如
[{'1','1','1','1'},{'1','1','1','1'},{'1','1','1','1'},{'1','1','1','1'}]
在每个单元格中,分成多列数据框?
考虑到列的每个单元格中的列表长度不同!
在左上图中,我们有第一列,在右边,我们正在观察我想要制作的结果。
解决方案
正如@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
推荐阅读
- javascript - 无法使用 node.js/puppeteer 连接到代理 IP
- javascript - module.exports = mongoose; 在需要“./database”时工作?
- linux - Linux中的中断是否排队
- python - 如何在python中抓取网站上的表格
- php - 如何修复“未定义索引:E:\Xammpp\htdocs\trms\index.php 中的页面”错误?
- javascript - 如何在运行时调整 Ionic 4 IonContent 的高度
- node.js - 将 MERN 应用程序部署到 Heroku 时出错
- ansible - jinja2 表达式引用库存集合作为参数传递给 shell 脚本
- c# - Xamarin.Forms.Skeleton - 是什么让插件的动画和 BackgroundColor 不出现?
- php - 注意:未定义索引:死机白屏中的主机