我有一个包含多个列的熊猫数据,我必须根据条件用true或false更新一个列。例如,列名为price和result,如果price列的值为promotion,则结果列应更新为true或Otherfalse。
请帮我处理这个。
发布于 2018-07-07 10:45:25
鉴于此,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发布于 2018-07-07 11:23:36
让我们假设dataframe如下所示:
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生成的dataframe如下所示:
price result
0 0 False
1 1 False
2 2 False
3 promotion True
4 3 False
5 promotion Truehttps://stackoverflow.com/questions/51222282
复制相似问题