Reputation: 123
I have a dataframe with a column called Dir that contains five values: N, S, E, W and C. I've split them into separate dataframes like so:
df_N = df[(df['Dir'] == 'N')]
df_S = df[(df['Dir'] == 'S')]
df_E = df[(df['Dir'] == 'E')]
df_W = df[(df['Dir'] == 'W')]
df_C = df[(df['Dir'] == 'C')]
However I'd like to create a function or list comprehension that does this for me so if the values in the data change, I don't have to re-code it.
I've created a list of the values like so:
CP_Vals = Series.unique(dftc2['iDir']).tolist()
But not having a great deal ofd experience in Python, I'm struggling to create something that automates this. I was thinking something like:
for x in CP_Vals:
df_x = df[(df['iDir'] == '%s' % x)]
Is this possible? Thanks in advance!
Upvotes: 2
Views: 87
Reputation: 90979
You can use a dictionary to store the different dataframes you get with the corresponding name of as key. Example -
CP_Vals = dftc2['iDir'].unique().tolist()
df_dict = {'df_{}'.format(x): df[(df['iDir'] == x)] for x in CP_Vals}
Please note, dictionary comprehension is only available in Python 2.7+. Also, after this you can access a particular DataFrame as df_dict['df_N']
, etc.
Upvotes: 4