将Dafaframe中的元组分成多行 [英] Getting a tuple in a Dafaframe into multiple rows

查看:83
本文介绍了将Dafaframe中的元组分成多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中有两列(客户,交易). 交易列是该客户所有交易ID的元组.

I have a Dataframe, which has two columns (Customer, Transactions). The Transactions column is a tuple of all the transaction id's of that customer.

Customer Transactions
1        (a,b,c)
2        (d,e)

我想将其转换为具有客户和交易ID的数据框,像这样.

I want to convert this into a dataframe, which has customer and transaction id's, like this.

Customer  Transactions
1         a
1         b
1         c
2         d
2         e

我们可以使用循环来做到这一点,但是这样做有1或2行的直线方式.

We can do it using loops, but is there a straight 1 or 2 lines way for doing that.

推荐答案

您可以使用 DataFrame 构造函数:

You can use DataFrame constructor:

df = pd.DataFrame({'Customer':[1,2],
                   'Transactions':[('a','b','c'),('d','e')]})

print (df)
   Customer Transactions
0         1    (a, b, c)
1         2       (d, e)

df1 = pd.DataFrame(df.Transactions.values.tolist(), index=df.Customer)
print (df1)
          0  1     2
Customer            
1         a  b     c
2         d  e  None

然后使用 stack 重塑:

Then reshape with stack:

print (df1.stack().reset_index(drop=True, level=1).reset_index(name='Transactions'))
   Customer Transactions
0         1            a
1         1            b
2         1            c
3         2            d
4         2            e

这篇关于将Dafaframe中的元组分成多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆