这是我的熊猫数据框,我想变平。我怎样才能做到这一点 ?
我的输入
key column
1 {'health_1': 45, 'health_2': 60, 'health_3': 34, 'health_4': 60, 'name': 'Tom'}
2 {'health_1': 28, 'health_2': 10, 'health_3': 42, 'health_4': 07, 'name': 'John'}
3 {'health_1': 86, 'health_2': 65, 'health_3': 14, 'health_4': 52, 'name': 'Adam'}
Run Code Online (Sandbox Code Playgroud)
预期输出
所有的health和name都会成为column name自己的一个与自己对应的values。没有特别的顺序。
health_1 health_2 health_3 health_4 name key
45 60 34 60 Tom 1
28 10 42 07 John 2
86 65 14 52 Adam 3
Run Code Online (Sandbox Code Playgroud)
你可以用一条线解决方案来做到这一点,
df_expected = pd.concat([df, df['column'].apply(pd.Series)], axis = 1).drop('column', axis = 1)
Run Code Online (Sandbox Code Playgroud)
完整版:
import pandas as pd
df = pd.DataFrame({"column":[
{'health_1': 45, 'health_2': 60, 'health_3': 34, 'health_4': 60, 'name': 'Tom'} ,
{'health_1': 28, 'health_2': 10, 'health_3': 42, 'health_4': 7, 'name': 'John'} ,
{'health_1': 86, 'health_2': 65, 'health_3': 14, 'health_4': 52, 'name': 'Adam'}
]})
df_expected = pd.concat([df, df['column'].apply(pd.Series)], axis = 1).drop('column', axis = 1)
print(df_expected)
Run Code Online (Sandbox Code Playgroud)
演示: https : //repl.it/repls/ButteryFrightenedFtpclient
| 归档时间: |
|
| 查看次数: |
6643 次 |
| 最近记录: |