更新熊猫数据框

时间:2018-07-07 10:31:49

标签: python-3.x pandas

我有一个包含多列的pandas数据框,我必须根据条件使用truefalse更新一列。例如,列名分别为priceresult,如果price列的值为promotion,则结果列应更新为true或{{1} }。

请帮助我。

2 个答案:

答案 0 :(得分:0)

给出此df:

       price  result
0  promotion       0
1          1       0
2          4       0
3          3       0

您可以这样做:

df['result'] = np.where(df['price'] == 'promotion', True, False)

输出:

      price  result
0  promotion    True
1          1   False
2          4   False
3          3   False

答案 1 :(得分:0)

让我们假设数据框看起来像这样:

    price     result
0   0          False
1   1          False
2   2          False
3   promotion  False
4   3          False
5   promotion  False

您可以创建两个布尔数组。第一个在结果列中要设置“ True”值的索引处将具有“ True”值,第二个在结果列中要设置“ False”值的索引处将具有“ True”值。 这是代码:

index_true = (df['price'] == 'promotion')
index_false = (df['price'] != 'promotion')

df.loc[index_true, 'result'] = True
df.loc[index_false, 'result'] = False

结果数据帧将如下所示:

    price   result
0   0        False
1   1        False
2   2        False
3   promotion   True
4   3        False
5   promotion   True