[英]Sort and Slice DataFrame in Pandas
我有一個如下所示的數據框:
detaildate detailquantity
0 2012-02-09 7.0
1 2011-05-27 -1.0
2 2011-05-04 -2.0
3 2012-03-19 -2.0
4 2012-03-18 -3.0
我想首先按detaildate
對上面的數據detaildate
進行排序,然后將數據detaildate
從detailquantity
的第一個正值detailquantity
到最后一個索引。
結果數據幀應如下所示:
detaildate detailquantity
0 2012-02-09 7.0
4 2012-03-18 -3.0
3 2012-03-19 -2.0
我正在嘗試下面的代碼,但是最后導致一個空的數據框,我無法弄清楚為什么
df.sort_values(by='detaildate', inplace=True)
df = df[df[df['detailquantity'] > 0].first_valid_index():]
上面的代碼有什么問題?
使用帶有布爾掩碼的Series.cumsum
並測試所有大於0
值,如果所有負值,解決方案也可以正常工作:
df.sort_values(by='detaildate', inplace=True)
df = df[(df['detailquantity'] > 0).cumsum() > 0]
print (df)
detaildate detailquantity
0 2012-02-09 7.0
4 2012-03-18 -3.0
3 2012-03-19 -2.0
應該通過創建唯一索引來更改您的解決方案,但必須至少匹配一個值:
df.sort_values(by='detaildate', inplace=True)
df = df.reset_index(drop=True)
df = df.loc[(df['detailquantity'] > 0).idxmax():]
print (df)
detaildate detailquantity
2 2012-02-09 7.0
3 2012-03-18 -3.0
4 2012-03-19 -2.0
numpy中的另一種選擇:
df.sort_values(by='detaildate', inplace=True)
df = df.iloc[(df['detailquantity'].values > 0).argmax():]
print (df)
detaildate detailquantity
0 2012-02-09 7.0
4 2012-03-18 -3.0
3 2012-03-19 -2.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.