Skip to content Skip to sidebar Skip to footer

Getting A Tuple In A Dafaframe Into Multiple Rows

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

Solution 1:

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

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

Solution 2:

I think following is faster:

import numpy as np
import random
import string
import pandas as pd
from itertools import chain

customer = np.unique(np.random.randint(0, 1000000, 100000))
transactions = [tuple(string.ascii_letters[:random.randint(3, 10)]) for _ in range(len(customer))]
df = pd.DataFrame({"customer":customer, "transactions":transactions})

df2 = pd.DataFrame({
        "customer": np.repeat(df.customer.values, df.transactions.str.len()),
        "transactions": list(chain.from_iterable(df.transactions))})

Post a Comment for "Getting A Tuple In A Dafaframe Into Multiple Rows"