arv
arv

Reputation: 398

Create new dataframe using globals

price
               price
date    
2010-01-04  34.57282657
2010-01-04  123.900000
2010-01-04  353.6789738
2010-01-04  13.08
2010-01-04  12.45

How can I create a first-differenced dataframe for each item in the list below? Code needs to be general. I tried:

listxx  = ["price"]
for x in listxx:
      globals().update({x_first_diff :x.diff().dropna()})
Expected Output:
price_first_diff 

             price_first_diff 
2010-01-04  
2010-01-04  89.33
...

Upvotes: 2

Views: 89

Answers (1)

MrNobody33
MrNobody33

Reputation: 6483

You are almost there, just use again globals to access to the dataframe, and formated strings to name the modified dataframe:

listxx  = ["price"]
for x in listxx:
      globals().update({f'{x}_first_diff':globals()[x].diff().fillna('')})

price_first_diff
#              price
#date               
#2010-01-04         
#2010-01-04  89.3272
#2010-01-04  229.779
#2010-01-04 -340.599
#2010-01-04    -0.63

You can also try to use dict comprehension to create the new dataframes, and then update globals:

listxx  = ["price"]
dc={f'{x}_first_diff' :globals()[x].diff().fillna('') for x in listxx}
globals().update(dc)

Upvotes: 1

Related Questions