[英]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 df
的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
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
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.