拆分pandas数据帧列中的元组列表

2024-04-25 03:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,其中每个元素都是元组的列表。在

import pandas as pd
data={'A':[[('potatoes',9),('cabbages',7),('carrots',5),('onions',2)]],
      'B':[[('cabbages',5),('apples',1),('plums',9),('peaches',6)]]}
df = pd.DataFrame(data).transpose()
print df
                                                  0
A  [(potatoes, 9), (cabbages, 7), (carrots, 5), (...
B  [(cabbages, 5), (apples, 1), (plums, 9), (peac...

我想把它分解成一个只包含每个元组元素的数据帧:

^{pr2}$

给予

               0              1             2             3
A  (potatoes, 9)  (cabbages, 7)  (carrots, 5)   (onions, 2)
B  (cabbages, 5)    (apples, 1)    (plums, 9)  (peaches, 6)

我想再深入一层,最终的结果是:

          0  1         2  3        4  5        6  7
A  potatoes  9  cabbages  7  carrots  5   onions  2
B  cabbages  5    apples  1    plums  9  peaches  6

我现在通过:

ww2 = pd.concat([ww[col].apply(pd.Series) for col in ww.columns], axis=1)
ww2.columns = range(ww2.shape[1])

但是有没有更好的方法来做这件事呢。更“熊猫”的方式?在


Tags: 数据元素dfdatapd元组wwapples
1条回答
网友
1楼 · 发布于 2024-04-25 03:34:52

见下文

ww3 = pd.DataFrame()    
l = len(ww.columns)
for i in range(l):
    ww3[i] = ww[i].apply(lambda x: x[0])
    ww3[i+l] = ww[i].apply(lambda x: x[1])
print (ww3)

          0  4         1  5        2  6        3  7
A  potatoes  9  cabbages  7  carrots  5   onions  2
B  cabbages  5    apples  1    plums  9  peaches  6

相关问题 更多 >