Alex Man
Alex Man

Reputation: 477

Add a list with varable len to a dataframe in Python?

I have a dataframe here:

>>> Import pandas as pd
>>> pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
     col1  col2
0     1     3
1     2     4
>>> df=pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df['col3']=""
>>> df['col4']=""
>>> df
     col1  col2 col3 col4
0     1     3
1     2     4

What I need to do is add the following list as rows of column 3 and 4.

lis1 = ['a', 'b']
lis2 = ['a']

The output should be something like this:

     col1  col2 col3 col4
0     1     3    a   b
1     2     4    a

Upvotes: 0

Views: 36

Answers (3)

BENY
BENY

Reputation: 323226

Try with

df = df.join(pd.DataFrame([lis1,lis2],columns=['col3','col4'],index=df.index))
df
Out[80]: 
   col1  col2 col3  col4
0     1     3    a     b
1     2     4    a  None

Upvotes: 1

wwnde
wwnde

Reputation: 26676

Try assign,pd.Series

df=df.assign(col3=pd.Series(lis1),col4=pd.Series(lis2 ))

    col1  col2 col3 col4
0     1     3    a    a
1     2     4    b  NaN

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

How about:

df.loc[0, ['col3','col4']] = lis1
df.loc[1, ['col3']] = lis2

Output:

   col1  col2 col3 col4
0     1     3    a    b
1     2     4    a  NaN

Upvotes: 0

Related Questions