2

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.

1
  • You want to have new columns added? Commented Jul 5, 2019 at 12:43

2 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

instead of concat, use df.merge(..., left_on='ColA', right_index=True).
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.