Reputation: 3375
Hi I have a dataframe like this:
ColA ColB
a 0
b 1
c 2
I want to append list_a = [ 0,1 ] to where column A == a and append list_c = [ 0, 1, 2 ] to where column A == c. Final should look something like this:
ColA ColB
a 0 0 1 Nan
b 1 Nan Nan Nan
c 2 0 1 2
How can I do this? Thank you.
Upvotes: 2
Views: 1027
Reputation: 2868
import pandas as pd
df = pd.DataFrame([['a',0],['b',1],['c',2]], columns= ['A','B'])
def compar_func(x):
if x == 'a':
return [0,1]
elif x == 'c':
return [0,1,2]
else:
return ''
df1= pd.DataFrame(df['A'].apply(compar_func).values.tolist())
pd.concat([df, df1], axis = 1)
#o/P
A B 0 1 2
0 a 0 0.0 1.0 NaN
1 b 1 NaN NaN NaN
2 c 2 0.0 1.0 2.0
Upvotes: 0
Reputation: 18647
You could construct your lists
into a DataFrame
and concat
them:
(pd.concat([df.set_index('ColA'),
pd.DataFrame([list_a, list_c], index=['a', 'c'])],
axis=1).rename_axis('ColA').reset_index())
[out]
ColA ColB 0 1 2
0 a 0 0.0 1.0 NaN
1 b 1 NaN NaN NaN
2 c 2 0.0 1.0 2.0
Or as @QuangHoang suggested, use DataFrame.merge
:
df.merge(pd.DataFrame([list_a, list_c], index=['a', 'c']),
left_on='ColA',
right_index=True,
how='left')
Upvotes: 2