Aki*_*aka 2 python reshape dataframe pandas
我的pandas数据框中的一列包含一个列表.我想扩展它并转换如下的垂直形状.怎么做?
前(代码):
import pandas as pd
pd.DataFrame({
'col1':['fruit', 'veicle', 'animal'],
'col2':['apple', 'bycicle', 'cat'],
'col3':[1,4,2],
'list':[
[10, 20],
[1.2, 3.0, 2.75],
['tommy', 'tom']
]
})
Run Code Online (Sandbox Code Playgroud)
前(表):
|col1 |col2 |col3|list |
|------|-------|----|----------------|
|fruit |apple | 1|[10, 20] |
|veicle|bicycle| 4|[1.2, 3.0, 2.75]|
|animal|cat | 2|['tommy', 'tom']|
Run Code Online (Sandbox Code Playgroud)
后
|col1 |col2 |col3|list |
|------|-------|----|-------|
|fruit |apple | 1|10 |
|fruit |apple | 1|20 |
|viecle|bycicle| 4|1.2 |
|viecle|bycicle| 4|3.0 |
|viecle|bycicle| 4|2.75 |
|animal|cat | 2|'tommy'|
|animal|cat | 2|'tom |
Run Code Online (Sandbox Code Playgroud)
注1:列表的长度和类型不同.
注2:我可以不修改代码生成datafarme.
谢谢你的阅读.
您可以set_index前三列,然后应用于pd.Series列的列,然后堆叠它们.
df.set_index(['col1','col2','col3'])['list'].apply(pd.Series).stack().reset_index().drop('level_3',axis=1)
Run Code Online (Sandbox Code Playgroud)
输出:
col1 col2 col3 0
0 fruit apple 1 10
1 fruit apple 1 20
2 veicle bycicle 4 1.2
3 veicle bycicle 4 3
4 veicle bycicle 4 2.75
5 animal cat 2 tommy
6 animal cat 2 tom
| 归档时间: |
|
| 查看次数: |
516 次 |
| 最近记录: |