0

Let's say I have 3 dataframes:

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.

I am trying this:

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

This is not working because name is a string. 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']

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Katty_one
  • 351
  • 1
  • 8
  • Does this answer your question? [How can I select a variable by (string) name?](https://stackoverflow.com/questions/47496415/how-can-i-select-a-variable-by-string-name) – Karl Knechtel Jul 05 '22 at 02:04

1 Answers1

3

Don't use the names in the list, but rather the variables (i.e., the dataframes) themselves:

dataframes = [df,da,db]

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

output: ['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]
mozway
  • 194,879
  • 13
  • 39
  • 75