[英]Compare multiple dates columns by row ID and highlight them in python or pandas
[英]In Python, compare row diffs for multiple columns
我想在多列上執行逐行比較。 我想要一個系列,指示一行中的所有條目(多個列)是否與前一行相同。
假設我有以下數據幀
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
你需要all
In [1306]: df.diff().eq(0).all(1)
Out[1306]:
0 False
1 True
2 False
3 False
4 True
dtype: bool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.