3

I have created a dictionary of dataframes to store my data. I need to do some stuff to each dataframe for which I'm trying to use iteritems() to iterate through the dictionary. But somehow i seem to be unable to actually do anything to the dataframes. Code compiles and does not throw any errors, it just seems to not do anything.

Here a simplification of my code:

This just makes a sample dictionary of dataframes

dic={}
df1=pd.DataFrame(np.random.randn(10,5),columns=['a','b','c','d','e'])
df2=pd.DataFrame(np.random.randn(10,5),columns=['a','b','c','d','e'])
df3=pd.DataFrame(np.random.randn(10,5),columns=['a','b','c','d','e'])
df4=pd.DataFrame(np.random.randn(10,5),columns=['a','b','c','d','e'])
df5=pd.DataFrame(np.random.randn(10,5),columns=['a','b','c','d','e'])

dic[1]=df1
dic[2]=df2
dic[3]=df3
dic[4]=df4
dic[5]=df5

And this is a basic set of things i want to do to each dataframe.

for key, item in dic.iteritems():
    item=item.reset_index()    
    item['Rank']=(item.index)+1

So, after the iteration I am expecting each dataframe to have an extra column with the old index, and another extra column with the "Rank" like so:

Expected

Instead the dataframe seems to be unaffected by the operations and looks the same as before:

Reality

I have tried also to use a temporary dataframe inside the iteration and then try to write it into "item" with the same result. I am just wondering if what i want to do is even possible or maybe i have to go around it and use a different method to achieve my goals.

Minoru Tsuru
  • 79
  • 1
  • 7

2 Answers2

1

I think you need assign DataFrame back only, also if want python 2 and 3 code use items():

for key, item in dic.items():
    item=item.reset_index()    
    item['Rank']=(item.index)+1
    dic[key] = item

print (dic[1])
   index         a         b         c         d         e  Rank
0      0 -1.085631  0.997345  0.282978 -1.506295 -0.578600     1
1      1  1.651437 -2.426679 -0.428913  1.265936 -0.866740     2
2      2 -0.678886 -0.094709  1.491390 -0.638902 -0.443982     3
3      3 -0.434351  2.205930  2.186786  1.004054  0.386186     4
4      4  0.737369  1.490732 -0.935834  1.175829 -1.253881     5
5      5 -0.637752  0.907105 -1.428681 -0.140069 -0.861755     6
6      6 -0.255619 -2.798589 -1.771533 -0.699877  0.927462     7
7      7 -0.173636  0.002846  0.688223 -0.879536  0.283627     8
8      8 -0.805367 -1.727669 -0.390900  0.573806  0.338589     9
9      9 -0.011830  2.392365  0.412912  0.978736  2.238143    10
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
-1

Assign item's dataframe back to dic[key]

for key, item in dic.items():
    item=item.reset_index()    
    item['Rank']=(item.index)+1
    dic[key] = item
Akshay Kandul
  • 592
  • 4
  • 10