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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With