subtraction of two loc values in python pandas

时间:2016-12-02 05:01:25

标签: python pandas

I have two value found from the following analysis:

v1= dd['y'].loc[dd['localtime']==dd['localtime'].max()]

v2= dd['y'].loc[dd['localtime']==dd['localtime'].min()]

the value is in the form:

v1
4906    4344.22552
Name: y, dtype: float64

v2
4785    5400.39864
Name: y, dtype: float64

How can I get the differce of this two value (v2-v1) as (5400.39864 - 4344.22552)?

2 个答案:

答案 0 :(得分:0)

If assigning v3 = v2 - v1 doesn't work, make sure they are of the same object type. However, it looks like you're trying to find a time difference, in which case I would look at Panda's inbuilt Time Delta functions

答案 1 :(得分:0)

我认为你可以使用:

v1 = pd.Series(4344.22552, index=[4906], name='y')
print (v1)
4906    4344.22552
Name: y, dtype: float64

v2 = pd.Series(5400.39864, index=[4785], name='y')
print (v2)
4785    5400.39864
Name: y, dtype: float64

values转换为numpy array的Substract值 - 获取length=1的数组,因此请[0]选择:

print (v2.values[0] - v1.values[0])
1056.17312

print ((v2.values - v1.values)[0])
1056.17312

或者按Series.iat选择v1v2的第一个值:

print (v2.iat[0] - v1.iat[0])
1056.17312

但我认为更好的是使用idxmaxidxmin

v1 = dd.loc[dd['localtime'].idxmax(), 'y']
v2=  dd.loc[dd['localtime'].idxmin(), 'y']

样品:

dd = pd.DataFrame({'localtime':[1,2,3,5],
                   'y':[5400.39864,2000,3000,4344.22552]}, 
                  index=[4785,4786,4788,4906])

print (dd)
      localtime           y
4785          1  5400.39864
4786          2  2000.00000
4788          3  3000.00000
4906          5  4344.22552

v1 = dd.loc[dd['localtime'].idxmax(), 'y']
v2 = dd.loc[dd['localtime'].idxmin(), 'y']

print (v2 - v1)
1056.17312