Reputation: 149
I want to create df_2008 to df_2014 from an original df by iteration. df has columns names '2008' to '2014' and I want to seperate them into different dfs.
I tried
for i in range(2008, 2015):
'df_'+str(i)=df[str(i)]
Which won't work.
I would really appreciate it if anyone could help me.
Upvotes: 3
Views: 2095
Reputation: 91009
To create variables by string, you can use - globals()
function , which returns the dictionary of global namespace, and then create a new element in that dictionary for your variable and set the value to the value you want.
Also , you can directly call - pandas.DataFrame(Series)
- and this would create the DataFrame for you, from the series.
Example -
import pandas as pd
gbl = globals()
for i in range(2008, 2015):
gbl['df_'+str(i)] = pd.DataFrame(df[str(i)])
Example code -
In [8]: d = pd.DataFrame([[1,2,3,4],[5,6,7,8]], columns = ['A','B','C','D'])
In [9]: d
Out[9]:
A B C D
0 1 2 3 4
1 5 6 7 8
In [10]: gbl = globals()
In [11]: gbl['e'] = pd.DataFrame(d['A'])
In [12]: e
Out[12]:
A
0 1
1 5
Upvotes: 2