spiff spiff - 3 months ago 7x
Python Question

Naming DataFrames iteritively using items from a List + a string

I have a list of names of countries.. and I have a large dataframe where one of the columns is ' COUNTRY ' (yes it has a space before and after the word country) I want to be create smaller DataFrames based on country names

cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]

seems too long a command to achieve this? It does work though.


str("%s_data" % (asia_country_list[1]))



but when I combine the above two:

str("%s_data" % (asia_country_list[1])) = cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]

I get:

SyntaxError: can't assign to function call

happy to learn other ways as well to achieve this pls.. Thanks vm


I don't think you should do this, but if you really need it :

exec(str("%s_data" % (asia_country_list[1])) +"= cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]") 

should work. Using a dictionary is likely to solve your problem

  D["%s_data" % (asia_country_list[1]))]=cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]]

EDIT : the first solution is a bad idea : exec is a dangerous command, if one column is named "del cleaned_df" you will actually execute it, it can get destructive. Typically I am guessing spaces are a problem in your case. It's a bit like SQL injections...