Converting tuples in a row to a new columns in Dataframe, must use pandas 0.21
I have column with list of tuples, and would like to convert this tuples into a new columns. (Note: must use pandas 0.21; cannot upgrade due to my project requirements.) Please see the example below:
df = pd.DataFrame(dict(a=[1,2,3],
b=['a', 'a', 'b'],
c=[[('pear', 1), ('apple', 2)], [('pear', 7), ('orange', 1)], [('apple', 9)] ]))
df
a b c
0 1 a [(pear, 1), (apple, 2)]
1 2 a [(pear, 7), (orange, 1)]
2 3 b [(apple, 9)]
and would like to convert it to
a b fruit value
0 1 a pear 1
1 1 a apple 2
2 2 a pear 7
3 2 a orange 1
4 3 b apple 9
I can do it but it is not really efficient, in my case I have more than 500K of rows. Is there a more efficient way of doing it?
UPDATE:
All three solutions proposed below are great for pandas >=0.25
. For earlier versions df.explode
is not an option. And for pandas < 0.24
there is no df.to_numpy
so only solution for earlier versions is @jezreal's solution
A small benchmark is below (pandas == 0.25)
(surprisingly explode is slower):
from itertools import product, chain
def sol_1(df):
phase1 = (product([a],b,c) for a,b,c in df.to_numpy())
phase2 = [(a,b,*c) for a, b, c in chain.from_iterable(phase1)]
return pd.DataFrame(phase2, columns = ["a","b","fruit","value"])
def sol_2(df):
df1 = pd.DataFrame([(k, *x) for k, v in df.c.items() for x in v],
columns=['i','fruit','value'])
df = df.merge(df1, left_index=True, right_on='i').drop('i', axis=1)
return df
def sol_3(df):
df = df.explode('c')
df[['fruit', 'value']] = pd.DataFrame(df['c'].tolist(), index=df.index)
del df['c']
return df
%timeit sol_1(df)
%timeit sol_2(df)
%timeit sol_3(df)
586 µs ± 6.39 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.8 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 28.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Idea is reshape values in list comprehension to new DataFrame and then use DataFrame.merge
:
df1 = pd.DataFrame([(k, *x) for k, v in df.pop('c').items() for x in v],
columns=['i','fruit','value'])
print (df1)
i fruit value
0 0 pear 1
1 0 apple 2
2 1 pear 7
3 1 orange 1
4 2 apple 9
df = df.merge(df1, left_index=True, right_on='i').drop('i', axis=1)
print (df)
a b fruit value
0 1 a pear 1
1 1 a apple 2
2 2 a pear 7
3 2 a orange 1
4 3 b apple 9
Give this a go and see if it works on your version :
from itertools import product,chain
#create a cartesian for each row in df
phase1 = (product([a],b,c) for a,b,c in df.to_numpy())
#unpack the third entry per row in the flattened iterable
phase2 = [(a,b,*c) for a, b, c in chain.from_iterable(phase1)]
#create dataframe
result = pd.DataFrame(phase2, columns = ["a","b","fruit","value"])
a b fruit value
0 1 a pear 1
1 1 a apple 2
2 2 a pear 7
3 2 a orange 1
4 3 b apple 9