Reputation: 10697
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
Reputation: 829
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)))
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
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
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