Issue
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']
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]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.