繁体   English   中英

在Pandas中对DataFrame进行排序和切片

[英]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进行排序,然后将数据detaildatedetailquantity的第一个正值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.

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