python-3.x - 熊猫用元组将数据框列扩展为多列和多行
问题描述
我有一个数据框,其中一列包含的元素是一个包含多个元组的列表。我想将每个元组转换为每个元素的列,并为每个元组创建一个新行。所以这段代码显示了我的意思和我想出的解决方案:
import numpy as np
import pandas as pd
a = pd.DataFrame(data=[['a','b',[(1,2,3),(6,7,8)]],
['c','d',[(10,20,30)]]], columns=['one','two','three'])
df2 = pd.DataFrame(columns=['one', 'two', 'A', 'B','C'])
print(a)
for index,item in a.iterrows():
for xtup in item.three:
temp = pd.Series(item)
temp['A'] = xtup[0]
temp['B'] = xtup[1]
temp['C'] = xtup[2]
temp = temp.drop('three')
df2 = df2.append(temp)
print(df2)
输出是:
one two three
0 a b [(1, 2, 3), (6, 7, 8)]
1 c d [(10, 20, 30)]
one two A B C
0 a b 1 2 3
0 a b 6 7 8
1 c d 10 20 30
不幸的是,我的解决方案需要 2 个小时才能在 55,000 行上运行!有没有更有效的方法来做到这一点?
解决方案
我们先分解列然后分解行
a=a.explode('three')
a=pd.concat([a,pd.DataFrame(a.pop('three').tolist(),index=a.index)],axis=1)
one two 0 1 2
0 a b 1 2 3
0 a b 6 7 8
1 c d 10 20 30
推荐阅读
- python - 如何将参数从 guizero 对象传递给函数?
- javascript - Ajax 成功总是在 if 语句中运行 else
- ios - iOS Firebase 分离观察者监听器
- java - 如何在 Java 中为数组创建 HeapSort 方法?
- c# - 处理 C# AggregateException 的正确方法
- powershell - 将脚本的退出代码设置为随机值以模拟间歇性故障
- testng - What's the meaning of FailedWithinSuccess in TestNG?
- loops - 在 Common Lisp 循环中定义局部变量
- python-3.x - 如何在不改变外部状态的情况下以函数式编写斐波那契?
- google-cloud-platform - PATH environment variable content on Compute Engine with different SSH access commands