使用名为“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 数据框 - 在特定条件下查找最长的连续行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40068261/