简体   繁体   English

将列表中的元素分配给数据框的不同列

[英]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. 我正在尝试将列表l的元素分配给df的不同列,但是找不到解决方法。 df.append(l) adds the list in one single column. df.append(l)将列表添加到一列中。

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
    ... ...

使用loc

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

We can use loc with the length of df : 我们可以使用loc length of dflength 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

You can using Series format your list then append 您可以使用Series格式list然后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
  1. You could use pd.concat to achieve exactly what you wanted: 可以使用pd.concat来实现所需的功能:
    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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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