Home > front end >  Add a list to a dataframe in Python
Add a list to a dataframe in Python

Time:07-05

I have a df

     col1  col2
0     1     AA
1     2     BB
2     3     CC
3     4     AA

and I have the following lists

list1 = ['a1', 'a2', 'a3']
list2 = ['b1', 'b2', 'b3']
list3 = ['c1', 'c2', 'c3']

I want to add the list values to different columns of particular rows in the df based on condition i.e., if col2 in df has AA ,the i need the list1 to be appended to that.

Expected output:

     col1  col2   1    2    3
0     1     AA   a1    a2   a3
1     2     BB   b1    b2   b3
2     3     CC   c1    c2   c3
3     4     AA   a1    a2   a3

Thanks

CodePudding user response:

You can play with pd.concat() and Pandas' Series.

df = pd.DataFrame({"col1":[1,2,3],"col2":[4,5,6]})

lst = pd.Series([7,8,9])

pd.concat((df,lst),axis=1)

CodePudding user response:

Check below provides required output.

import pandas as pd
import numpy as np 

df_1 = pd.DataFrame(  {'col1':[1,2,3,4,], 'col2':['AA','BB','CC','AA']})

list1 = ['a1', 'a2', 'a3']
list2 = ['b1', 'b2', 'b3']
list3 = ['c1', 'c2', 'c3']


df = pd.DataFrame([list1, list2, list3], columns=['1','2','3'])

df['col2'] = df['1'].str.split('', expand=True)[1].str.upper()*2

pd.merge(df_1, df, left_on='col2',right_on='col2')

enter image description here

  • Related