Python: Accessing The Proper Values In An Array
I want to calculate the following equation: calc = value_a(2D) - (value_b(0D) + value_b(1D))/10000 value_a(2D) corresponds to type **a**, year **2D** and value **1.1275** value_b(
Solution 1:
It looks like you really could use a multi-index here:
In [4]:df.reset_index(inplace=True)In [5]:dfOut[5]:typeyeardatevalue0a2D2015-02-09 1.12751b10M2015-02-09 58.12502b11M2015-02-09 68.37503b1M2015-02-09 3.34504b1W2015-02-09 0.89005b1Y2015-02-09 79.37506b2M2015-02-09 7.53507b2W2015-02-09 1.80008b3M2015-02-09 11.61009b3W2015-02-09 2.480010b4M2015-02-09 16.200011b5M2015-02-09 21.650012b6M2015-02-09 27.100013b7M2015-02-09 33.625014b8M2015-02-09 41.375015b9M2015-02-09 49.500016b0D2015-02-09 0.000017b1D2015-02-09 0.1250In [6]:df.set_index(['type','year'],inplace=True)In [7]:dfOut[7]:datevaluetypeyeara2D2015-02-09 1.1275b10M2015-02-09 58.125011M2015-02-09 68.37501M2015-02-09 3.34501W2015-02-09 0.89001Y2015-02-09 79.37502M2015-02-09 7.53502W2015-02-09 1.80003M2015-02-09 11.61003W2015-02-09 2.48004M2015-02-09 16.20005M2015-02-09 21.65006M2015-02-09 27.10007M2015-02-09 33.62508M2015-02-09 41.37509M2015-02-09 49.50000D2015-02-09 0.00001D2015-02-09 0.1250
Then simply:
In[8]: df.loc['a','2D'].value- (df.loc['b', '0D'].value + df.loc['b','1D'].value)/10000Out[8]: 1.1274875
Note, suppose I have multiple years (this I made by simply concatenating the df to itself):
In [24]:df2Out[24]:typeyeardatevalue0a2D2015-02-09 1.12751b10M2015-02-09 58.12502b11M2015-02-09 68.37503b1M2015-02-09 3.34504b1W2015-02-09 0.89005b1Y2015-02-09 79.37506b2M2015-02-09 7.53507b2W2015-02-09 1.80008b3M2015-02-09 11.61009b3W2015-02-09 2.480010b4M2015-02-09 16.200011b5M2015-02-09 21.650012b6M2015-02-09 27.100013b7M2015-02-09 33.625014b8M2015-02-09 41.375015b9M2015-02-09 49.500016b0D2015-02-09 0.000017b1D2015-02-09 0.125018a2D2015-02-10 1.127519b10M2015-02-10 58.125020b11M2015-02-10 68.375021b1M2015-02-10 3.345022b1W2015-02-10 0.890023b1Y2015-02-10 79.375024b2M2015-02-10 7.535025b2W2015-02-10 1.800026b3M2015-02-10 11.610027b3W2015-02-10 2.480028b4M2015-02-10 16.200029b5M2015-02-10 21.650030b6M2015-02-10 27.100031b7M2015-02-10 33.625032b8M2015-02-10 41.375033b9M2015-02-10 49.500034b0D2015-02-10 0.000035b1D2015-02-10 0.1250In [25]:df.iloc[-2,-1]=100000# this corresponds to (b, 0D) and used to be 0
As @cᴏʟᴅsᴘᴇᴇᴅ noted, you can group by the 'date'
column:
In [26]: df2.groupby('date').apply(
...: lambda df:
...: df.loc['a','2D'].value
...: - (df.loc['b', '0D'].value + df.loc['b','1D'].value)
...: / 10000
...: )
Out[27]:
date
2015-02-091.1274872015-02-10 -8.872513
dtype: float64
Post a Comment for "Python: Accessing The Proper Values In An Array"