[英]How to add element from list to a dataframe as column preserving the order?
Imagine I have a list of three dataframes and a list with three names.想象一下,我有一个包含三个数据框的列表和一个包含三个名称的列表。
df1 = pd.DataFrame({'a':[0,1,2],
'b':[2,3,1]})
df2 = pd.DataFrame({'a':[1,1,2],
'b':[2,2,1]})
df3 = pd.DataFrame({'a':[0,2,2],
'b':[3,3,3]})
df_list = [df1, df2, df3]
names = ['df1', 'df2', 'df3']
I would like to add a new column called 'DF_NAME' to each dataframe from the list with the items inside the other list 'names'.我想为列表中的每个 dataframe 添加一个名为“DF_NAME”的新列,其中的项目位于另一个列表“名称”中。 And this should be done in the order they appeared, so the result for each dataframe should be:
这应该按照它们出现的顺序完成,所以每个 dataframe 的结果应该是:
a b DF_NAME
0 0 2 df1
1 1 3 df1
2 2 1 df1
a b DF_NAME
0 1 2 df2
1 1 2 df2
2 2 1 df2
a b DF_NAME
0 0 3 df3
1 2 3 df3
2 2 3 df3
I'm trying to do a loop like this, but it just adds the last name of the list.我正在尝试执行这样的循环,但它只是添加了列表的姓氏。 Could you help me?
你可以帮帮我吗?
for data in df_list:
for n in names:
data['DF_NAME'] = n
Try zip
:尝试
zip
:
for df, name in zip(df_list, names):
df['DF_NAME'] = name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.