gpt4 book ai didi

python - 在Python中,比较多列的行差异

转载 作者:行者123 更新时间:2023-11-30 22:31:16 24 4
gpt4 key购买 nike

我想对多列执行逐行比较。我想要一个系列,指示一行(几列)中的所有条目是否与前一行相同。

假设我有以下数据框

import pandas as pd
df = pd.DataFrame({'A' : [1, 1, 1, 2, 2],
'B' : [2, 2, 3, 3, 3],
'C' : [1, 1, 1, 2, 2]})

我可以比较所有行、所有列

>>> df.diff().eq(0)
A B C
0 False False False
1 True True True
2 True False True
3 False True False
4 True True True

这给出了一个单独比较每个系列的数据框。我想要的是一个系列中所有列的比较。

我可以通过循环来实现这一点

compare_all = df.diff().eq(0)
compare_tot = compare_all[compare_all.columns[0]]
for c in compare_all.columns[1:]:
compare_tot = compare_tot & compare_all[c]

这给出

>>> compare_tot
0 False
1 True
2 False
3 False
4 True
dtype: bool
正如预期的那样。

是否可以使用单行(即没有循环)来实现这一目标?

最佳答案

>>> (df == df.shift()).all(axis=1)
0 False
1 True
2 False
3 False
4 True
dtype: bool

关于python - 在Python中,比较多列的行差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45854425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com