我的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']
]
})
前(表):
^{pr2}$之后
|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 |
注1:列表的长度和类型不同。在
注2:我可以修改生成datafarme的代码。在
谢谢你的阅读。在
前几天从piR那里学到了这个很酷的技巧,使用了}:
np.repeat
和{性能
小
^{pr2}$大
作为1号线,巴拉斯的回答很短,但很慢。这里有一个改进,它使用dataframe构造函数而不是
df.apply
,在大数据上实现200x的加速:小
大
您可以设置前三列的索引,然后将
pd.Series
应用于list的列,然后将它们堆叠起来。在输出:
^{pr2}$下面是你完成这项任务的大致方法。这不是确切的解决方案,但会让您了解如何完成任务:
相关问题 更多 >
编程相关推荐