简体   繁体   English

如何迭代数据框名称列表以获取列表中每个数据框第一行的第一个值

[英]How to iterate of a list of dataframe's name to get the 1st value of 1st row of every dataframe in the list

Let's say I have 3 dataframes:假设我有 3 个数据框:

df=pd.DataFrame({'area':['lab','class_room','pool','gardem'],'%_chance':[0.33,0.27,.30,.10]})
da=pd.DataFrame({'city':['jess','nobytown','paris','miami'],'%_chance':[0.5,0.30,.15,.05]})
db=pd.DataFrame({'country':['china','japan','france','eua'],'%_chance':[0.43,0.27,.20,.10]})

and a list with the dataframe's name:以及带有数据框名称的列表:

dataframe_list_name = ['df','da','db']

I want to get the value of the first row of the first column of every dataframe(in this case there's only 3 but I can have more) and append them to a list.我想获取每个数据帧第一列的第一行的值(在这种情况下只有 3 个,但我可以有更多)并将它们附加到一个列表中。

I am trying this:我正在尝试这个:

f=[]
for name in dataframe_names:
    x=name.iloc[0,0]

This is not working because name is a string.这不起作用,因为 name 是一个字符串。 My question is: How can I iterate over that dataframe's name list to make thi code works?我的问题是:如何迭代该数据框的名称列表以使该代码有效?

The output should be:输出应该是:

f=['lab','jess','china'] f=['实验室','杰斯','中国']

Don't use the names in the list, but rather the variables (ie, the dataframes) themselves:不要使用列表中的名称,而是使用变量(即数据框)本身:

dataframes = [df,da,db]

f = [d.iat[0,0] for d in dataframes]

output: ['lab', 'jess', 'china']输出: ['lab', 'jess', 'china']

It is theoretically possible to use the names, but thus is a bad practice and makes the code poorly explicit and prone to bugs/errors/unwanted behavior (so don't do it please!):理论上可以使用这些名称,但这是一种不好的做法,并且会使代码不明确并且容易出现错误/错误/不需要的行为(所以请不要这样做!):

dataframe_list_name = ['df','da','db']
g = globals()

f = [g[name].iat[0,0] for name in dataframe_list_name]

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

相关问题 如何在python数据框中的列中获取值的第一次出现 - How to get the 1st occurence of a value in a column in python dataframe 如何将列表的第一个值更改为浮点型 - How to change the 1st value of a list to a float fillna() 仅填充 dataframe 的第一个值 - fillna() only fills the 1st value of the dataframe 如何合并 2 dataframe,创建只出现在第二个 dataframe 但不出现在第一个的行和 groupby 求和? - How to combine 2 dataframe, create a row that appear only in the second dataframe but not in the 1st and groupby to get the sum? 如何用另一个列表更新子列表的第一个值 - How to update the 1st value of the sub list with another list 如何将单独列的第一行附加到列表列表中 - How to append the 1st row of separate columns to a list of lists pandas.DataFrame.rolling 根据 Id 和时间索引将当前行值和下 2 行值相加,到第 1 行的值 - pandas.DataFrame.rolling summing the current row value and the next 2 row value based on Id and time index, to the 1st row's value 访问包含列表的 Pandas DataFrame 列的每个第一个元素 - Accessing every 1st element of Pandas DataFrame column containing lists for 循环 - 一个列表中的第一个值到第二个列表中的第一个值 - for loop - 1st value in one list to 1st value second list 根据熊猫中的条件更改数据框的第一行 - Change 1st row of a dataframe based on a condition in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM