比较 pandas 数据框行

Comparing pandas dataframe rows

我有一个像这样的数据框:

df = pd.DataFrame({30: {'2020-10-09': 12.79, '2020-10-12': 12.83, '2020-10-13': 12.88, '2020-10-14': 12.93, '2020-10-15': 12.99, '2020-10-16': 13.07, '2020-10-19': 13.16, '2020-10-20': 13.24, '2020-10-21': 13.32, '2020-10-22': 13.42}, 365: {'2020-10-09': 12.27, '2020-10-12': 12.27, '2020-10-13': 12.28, '2020-10-14': 12.29, '2020-10-15': 12.29, '2020-10-16': 13.07, '2020-10-19': 12.31, '2020-10-20': 12.32, '2020-10-21': 12.32, '2020-10-22': 12.33}})

我想找到所有列的值都相等的行。我可以使用 .loc 来做到这一点,但这意味着我必须对列名进行硬编码,我不想这样做,因为将来我可能会有更多的列进行比较。我很接近

df.eq(df.iloc[:, 0], axis=0)

给出

             30     365
2020-10-09  True    False
2020-10-12  True    False
2020-10-13  True    False
2020-10-14  True    False
2020-10-15  True    False
2020-10-16  True    True
2020-10-19  True    False
2020-10-20  True    False
2020-10-21  True    False
2020-10-22  True    False

但我无法检索每列中带有 True 的行。我认为使用 df[df.eq(df.iloc[:, 0], axis=0)] 应该可行,但它会产生多索引错误。谢谢!

您可以添加DataFrame.all for test if all Trues and use boolean indexing:

df = df[df.eq(df.iloc[:, 0], axis=0).all(axis=1)]
print (df)
              30     365
2020-10-16  13.07  13.07