我有一个以日期为索引的 Pandas 数据框。例如:
B group
index
2018-08-19 True
2018-08-20 True
2018-09-15 False
2018-09-15 False
2019-04-28 True
2019-06-01 False
2019-06-08 True
我只想选择每个可用月份的第一个元素。例如在这个 DF 中我想选择这些:
B group
index
2018-08-19 True
2018-09-15 False
2019-04-28 True
2019-06-01 False
我不知道该怎么做。所以我在这里问。提前致谢。
最佳答案
通过 DatetimeIndex.to_period
将 DatetimeIndex
转换为月份然后按 Series.duplicated
过滤带倒置面具和boolean indexing
:
df = df[~df.index.to_period('m').duplicated()]
print (df)
B group
2018-08-19 True
2018-09-15 False
2019-04-28 True
2019-06-01 False
关于 Pandas 日期索引 : select the first element of each month,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59551804/