gpt4 book ai didi

python - Pandas 数据帧 : how can i compare values in two columns of a row are equal to the ones in the same columns of a subsequent row?

转载 作者:行者123 更新时间:2023-12-04 01:03:25 26 4
gpt4 key购买 nike

假设我有一个像这样的数据框

Fruit  Color  Weight
apple red 50
apple red 75
apple green 45
orange orange 80
orange orange 90
orange red 90

我想根据第 x 行的 Fruit 和 Color 等于第 x+1 行的 Fruit 和 Color 来添加 True 或 False 列,如下所示:

Fruit  Color  Weight Validity
apple red 50 True
apple red 75 False
apple green 45 False
orange orange 80 True
orange orange 90 False
orange red 90 False

我尝试了以下方法,但我猜有一些错误,我得到了错误的结果:

g['Validity'] = (g[['Fruit', 'Color']] == g[['Fruit', 'Color']].shift()).any(axis=1) 

最佳答案

您对移动比较的想法是正确的,但您需要向后移动,以便将当前行与下一行进行比较。最后使用 all 条件强制行中的所有列都相等:

df['Validity'] = df[['Fruit', 'Color']].eq(df[['Fruit', 'Color']].shift(-1)).all(axis=1)

df
Fruit Color Weight Validity
0 apple red 50 True
1 apple red 75 False
2 apple green 45 False
3 orange orange 80 True
4 orange orange 90 False
5 orange red 90 False

关于python - Pandas 数据帧 : how can i compare values in two columns of a row are equal to the ones in the same columns of a subsequent row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67350600/

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