简体   繁体   中英

Pandas series – lowest value in last x rows

I am trying to build function that prints lowest value in last 10 rows into new column of my Pandas Dataframe hData.market_data["AAPL"]:

    close   volume  open    high    low
2015-11-11  116.110001  45218000    116.370003  117.419998  115.209999
2015-11-12  115.720001  32262600    116.260002  116.820000  115.650002
2015-11-13  112.339996  45164100    115.199997  115.570000  112.269997
2015-11-16  114.180000  37651000    111.379997  114.239998  111.000000
2015-11-17  113.690002  27254000    114.919998  115.050003  113.320000
2015-11-18  117.290001  46163400    115.760002  117.489998  115.500000
2015-11-19  118.779999  42908200    117.639999  119.750000  116.760002
2015-11-20  119.300003  34103500    119.199997  119.919998  118.849998
2015-11-23  117.750000  32266700    119.269997  119.730003  117.339996
2015-11-24  118.879997  42426900    117.330002  119.349998  117.120003

I came with this:

lowestlow = hData.market_data["AAPL"].low[-10:].min()
hData.market_data["AAPL"]["Lowestlow10"] = lowestlow

but it prints the same minimum calculated from last 10 rows of the whole series (instead of the lowest low of last 10 rows that is calculated through the series). Can you please advise me how to do it properly?

IIUC then you want rolling_min :

In [93]:
df['lowest_10'] = pd.rolling_min(df['low'],window=3)
df

Out[93]:
                 close    volume        open        high         low  \
2015-11-11  116.110001  45218000  116.370003  117.419998  115.209999   
2015-11-12  115.720001  32262600  116.260002  116.820000  115.650002   
2015-11-13  112.339996  45164100  115.199997  115.570000  112.269997   
2015-11-16  114.180000  37651000  111.379997  114.239998  111.000000   
2015-11-17  113.690002  27254000  114.919998  115.050003  113.320000   
2015-11-18  117.290001  46163400  115.760002  117.489998  115.500000   
2015-11-19  118.779999  42908200  117.639999  119.750000  116.760002   
2015-11-20  119.300003  34103500  119.199997  119.919998  118.849998   
2015-11-23  117.750000  32266700  119.269997  119.730003  117.339996   
2015-11-24  118.879997  42426900  117.330002  119.349998  117.120003   

             lowest_10  
2015-11-11         NaN  
2015-11-12         NaN  
2015-11-13  112.269997  
2015-11-16  111.000000  
2015-11-17  111.000000  
2015-11-18  111.000000  
2015-11-19  113.320000  
2015-11-20  115.500000  
2015-11-23  116.760002  
2015-11-24  117.120003  

So I think the following should work for you:

lowestlow=pd.rolling_min(hData.market_data["AAPL"].low, window=10)
hData.market_data["AAPL"]["Lowestlow10"]=lowestlow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM