熊猫数据框-查找符合特定条件的最长连续行

红花菜豆

使用名为“ df”的熊猫数据框,如下所示

             A
2015-05-01  True
2015-05-02  True
2015-05-03  False
2015-05-04  False
2015-05-05  False
2015-05-06  False
2015-05-07  True
2015-05-08  False
2015-05-09  False

我想返回一个切片,该切片是列'A'读为'False'的最长连续行数。能做到吗?

罗曼

您可以cumsum用来检测Aboolean中的变化,就像在python中可以求和一样。

# Test data
df= DataFrame([True, True, False, False, False, False, True, False, False], 
              index=pd.to_datetime(['2015-05-01', '2015-05-02', '2015-05-03',
                                   '2015-05-04', '2015-05-05', '2015-05-06',
                                   '2015-05-07', '2015-05-08', '2015-05-09']), 
              columns=['A'])

# We have to ensure that the index is sorted
df.sort_index(inplace=True)
# Resetting the index to create a column
df.reset_index(inplace=True)

# Grouping by the cumsum and counting the number of dates and getting their min and max
df = df.groupby(df['A'].cumsum()).agg(
    {'index': ['count', 'min', 'max']})

# Removing useless column level
df.columns = df.columns.droplevel()

print(df)
#    count        min        max
# A                             
# 1      1 2015-05-01 2015-05-01
# 2      5 2015-05-02 2015-05-06
# 3      3 2015-05-07 2015-05-09

# Getting the max
df[df['count']==df['count'].max()]

#    count        min        max
# A                             
# 2      5 2015-05-02 2015-05-06

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章