Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading