python - 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
解决方案
如果所有数据都是所有行中的元组并且所有列concat
与DataFrame
构造函数和一起使用,则解决方案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
推荐阅读
- javascript - JavaScript D3:缩放
- c# - 如何判断代码是为常规 .NET 还是 .NET Core 编写的?
- c# - 如何在发布模式下禁用 Console.WriteLine()?
- python - TensorFlow 神经网络连接不正确,但缺少什么?
- html - 立场:绝对没有做我所期望的
- list - 将“Textarea”对象从 iPython wigdet 转换为列表或可迭代数组
- java - Java - 访问类变量
- node.js - Knex.js:如何使用 for 循环插入多个数据?
- python - Python中的高效时间限制队列?
- python-2.7 - pip install ansible 目录所有者错误