[英]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.