熊猫比较行与条件

时间:2021-06-08 12:38:40

标签: python pandas

假设我们有一个如下所示的示例数据框,

df = pd.DataFrame(np.array([['strawberry', 'red', 3], ['apple', 'red', 6], ['apple', 'red', 5],
                           ['banana', 'yellow', 9], ['pineapple', 'yellow', 5], ['pineapple', 'yellow', 7],
                           ['apple', 'green', 2],['apple', 'green', 6], ['kiwi', 'green', 6]
                           ]),
               columns=['Fruit', 'Color', 'Quantity'])

df

    Fruit       Color    Quantity
0   strawberry  red         3
1   apple       red         6
2   apple       red         5
3   banana     yellow       9
4   pineapple  yellow       5
5   pineapple  yellow       7
6   apple      green        2
7   apple      green        6
8   kiwi       green        6

在这个 df 中,我正在逐行检查 Fruit 列是否有任何变化。

使用 shift() 方法行偏移 1,使用 fillna() 方法填充 NaN 值,最后使用 ne() 方法完成 True-False 标记。

因此您可以从索引 1 中检查,草莓变为苹果,结果为“真”。 索引2,没有变化,就是“False”。

df['Fruit_Check'] = df.Fruit.shift().fillna(df.Fruit).ne(df.Fruit)
df
        Fruit        Color      Quantity    Fruit_Check
0     strawberry      red          3        False
1       apple         red          6        True
2       apple         red          5        False
3      banana        yellow        9        True
4     pineapple      yellow        5        True
5     pineapple      yellow        7        False
6       apple        green         2        True
7       apple        green         6        False
8       kiwi         green         6        True

我的问题是:我还想检查“颜色”列。如果那里有变化, Fruit_Check 列必须是 False 默认值。所以 df 应该是这样的,

df
        Fruit        Color      Quantity    Fruit_Check
0     strawberry      red          3        False
1       apple         red          6        True
2       apple         red          5        False
3      banana        yellow        9        False
4     pineapple      yellow        5        True
5     pineapple      yellow        7        False
6       apple        green         2        False
7       apple        green         6        False
8       kiwi         green         6        True

我也不应该使用 for 循环。因为当我使用我的原始数据时,会花费太多时间。

1 个答案:

答案 0 :(得分:2)

每组使用 DataFrameGroupBy.shift 表示 shift

df['Fruit_Check'] = df.groupby('Color').Fruit.shift().fillna(df.Fruit).ne(df.Fruit)
print (df)
        Fruit   Color Quantity  Fruit_Check
0  strawberry     red        3        False
1       apple     red        6         True
2       apple     red        5        False
3      banana  yellow        9        False
4   pineapple  yellow        5         True
5   pineapple  yellow        7        False
6       apple   green        2        False
7       apple   green        6        False
8        kiwi   green        6         True