栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python Pandas list列表数据列拆分成多行的方法实现

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Pandas list列表数据列拆分成多行的方法实现

1、实现的效果

示例代码:

df=pd.Dataframe({'A':[1,2],'B':[[1,2],[1,2]]})
df
Out[458]: 
  A    B
0 1 [1, 2]
1 2 [1, 2]

拆分成多行的效果:

   A  B
0  1  1
1  1  2
3  2  1
4  2  2

2、拆分成多行的方法

1)通过apply和pd.Series实现

容易理解,但在性能方面不推荐。

df.set_index('A').B.apply(pd.Series).stack().reset_index(level=0).rename(columns={0:'B'})
Out[463]: 
  A B
0 1 1
1 1 2
0 2 1
1 2 2

2)使用repeat和Dataframe构造函数

性能可以,但不太适合多列

df=pd.Dataframe({'A':df.A.repeat(df.B.str.len()),'B':np.concatenate(df.B.values)})
df
Out[465]: 
  A B
0 1 1
0 1 2
1 2 1
1 2 2

或者

s=pd.Dataframe({'B':np.concatenate(df.B.values)},index=df.index.repeat(df.B.str.len()))
s.join(df.drop('B',1),how='left')
Out[477]: 
  B A
0 1 1
0 2 1
1 1 2
1 2 2

3)创建新的列表

pd.Dataframe([[x] + [z] for x, y in df.values for z in y],columns=df.columns)
Out[488]: 
  A B
0 1 1
1 1 2
2 2 1
3 2 2

或者

#拆成多于两列的情况
s=pd.Dataframe([[x] + [z] for x, y in zip(df.index,df.B) for z in y])
s.merge(df,left_on=0,right_index=True)
Out[491]: 
  0 1 A    B
0 0 1 1 [1, 2]
1 0 2 1 [1, 2]
2 1 1 2 [1, 2]
3 1 2 2 [1, 2]

4)使用reindex和loc实现

df.reindex(df.index.repeat(df.B.str.len())).assign(B=np.concatenate(df.B.values))
Out[554]: 
  A B
0 1 1
0 1 2
1 2 1
1 2 2
#df.loc[df.index.repeat(df.B.str.len())].assign(B=np.concatenate(df.B.values)

5)使用numpy高性能实现

newvalues=np.dstack((np.repeat(df.A.values,list(map(len,df.B.values))),np.concatenate(df.B.values)))
pd.Dataframe(data=newvalues[0],columns=df.columns)
  A B
0 1 1
1 1 2
2 2 1
3 2 2

到此这篇关于Python Pandas list列表数据列拆分成多行的方法实现的文章就介绍到这了,更多相关Pandas list列拆分成多行内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/15924.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号