Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: split a row to two or more rows when applying a row-wise function

I have a dataframe in pandas that looks like this:

df = pd.DataFrame([[4, 9],[4,9],[[1,2],[3,4]]], columns=['A', 'B'])
df

    A   B
0   4   9
1   4   9
2   [1, 2]  [3, 4]

However I would like to transform it to a table like this:

    A   B
0   4   9
1   4   9
2   1   2
3   3   4

Is there a way to apply a row wise function (using df.apply(function,axis=1,...) or some other function in pandas) to do that?

like image 532
Ohm Avatar asked Oct 27 '25 10:10

Ohm


2 Answers

Use lis comprehension with flatten values by chain:

from  itertools import chain

out = list(chain.from_iterable(item if isinstance(item[0],list) 
             else [item] for item in df[['A','B']].values))
df1 = pd.DataFrame(out, columns=['A','B'])

Or loop alternative:

out = []
for x in df[['A','B']].values:
    if isinstance(x[0], list):
        for y in x:
            out.append(y)
    else:
        out.append(x)

df1 = pd.DataFrame(out, columns=['A','B'])
print (df1)
   A  B
0  4  9
1  4  9
2  1  2
3  3  4
like image 133
jezrael Avatar answered Oct 29 '25 23:10

jezrael


Using list comprehension with concat:

df = pd.DataFrame([[4, 9],[4,9],[[1,2],[3,4]],], columns=['A', 'B'])

print (pd.concat([df.loc[:1], *[pd.DataFrame(list(i),columns=df.columns) for i in df.loc[2:].to_numpy()]],
                 ignore_index=True))
   A  B
0  4  9
1  4  9
2  1  2
3  3  4
like image 24
Henry Yik Avatar answered Oct 30 '25 01:10

Henry Yik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!