首页 > 解决方案 > 熊猫将行与条件进行比较

问题描述

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

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() 方法完成真假标签。

所以你可以从索引 1 中检查,草莓变成苹果,它将是“真”。索引 2,没有变化,它将是“假”。

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 循环。因为当我使用原始数据时,会花费太多时间。

标签: pythonpandas

解决方案


用于每组DataFrameGroupBy.shiftshift

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

推荐阅读