python - pandas dataframe - 查找具有特定条件的最长连续行

标签 python pandas dataframe

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

             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 来检测 A 列的变化,因为 python 中的 boolean 可以求和。

# 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

关于python - pandas dataframe - 查找具有特定条件的最长连续行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068261/

相关文章:

python - 如何使用 .corr() Pearson Correlation 获取 DataFrame 中两个选定列之间的相关性

Python 字符串格式 : is '%' more efficient than 'format' function?

python - Pypy 是否支持 PyTables 和 Numpy?

python - 尝试转换格式为 10/2/2012 9:00:00 AM 时出现错误 : invalid unit abbreviation:/,

java - Spark : rewrite . 过滤器 ("count > 1") 没有字符串表达式

python - 如何并行循环以更改 Python 字典中的对象?

python - 从索引到条件从 Pandas DataFrame 获取行

python - 如何在 Pandas 的条件下进行减法

python-3.x - 使用 Python 设置特定组的列上限

python - 从 Pandas 中的 groupby .agg() 或 .apply() 有效地创建全新的数据框?