HappyPy
HappyPy

Reputation: 10697

assign elements in a list to different columns in a dataframe

l = [1,2]
df = pd.DataFrame(columns=['x','y'])

I'm trying to assign the elements of list l to the different columns in df but cannot find a way to do this. df.append(l) adds the list in one single column.

I would also like to be able to append other lists I create subsequently

l2 = [3,4]
df.append(l2)

This is the expected output

>>> df 
    x   y
    1   2
    3   4
    ... ...

Upvotes: 1

Views: 813

Answers (4)

Yaniv
Yaniv

Reputation: 829

  1. You could use pd.concat to achieve exactly what you wanted:
    columns = ['x','y']
    df = pd.DataFrame(columns=columns)

and then add "rows" like so:

   l = [1,2]
   df = pd.concat((df, pd.DataFrame(data=[l], columns=columns)))
   l = [3,4]
   df = pd.concat((df, pd.DataFrame(data=[l], columns=columns)))
  1. However, you could also do something like the following (if it makes sense in your real use case):
   my_data = []
   my_data.append([1,2])
   my_data.append([3,4])
   # ...and then eventually:
   df = pd.DataFrame(my_data, columns=list('xy'))

Upvotes: 1

Erfan
Erfan

Reputation: 42886

We can use loc with the length of df:

l = [1,2]
df = pd.DataFrame(columns=['x','y'])
df.loc[len(df)] = l

print(df,'\n')

l2 = [3,4]

df.loc[len(df)] = l2

print(df)
   x  y
0  1  2 

   x  y
0  1  2
1  3  4

Upvotes: 2

rafaelc
rafaelc

Reputation: 59274

Use loc

df.loc[len(df), :] = l

Upvotes: 2

BENY
BENY

Reputation: 323226

You can using Series format your list then append

df=df.append(pd.Series(l,index=df.columns,name=0))
l2 = [3,4]
df=df.append(pd.Series(l2,index=df.columns,name=1))
df
Out[424]: 
   x  y
0  1  2
1  3  4

Upvotes: 1

Related Questions