简体   繁体   中英

Python Pandas: Assign lists with different lengths as a row to pandas dataframe

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.

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')
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM