Python 3.x 更新数据帧
我有一个包含多列的数据框,我必须根据条件用Python 3.x 更新数据帧,python-3.x,pandas,Python 3.x,Pandas,我有一个包含多列的数据框,我必须根据条件用true或false更新一列。示例列名称为price和result,如果price列的值为promotion,则结果列应更新为true或false 请帮我解决这个问题。鉴于此df: price result 0 promotion 0 1 1 0 2 4 0 3 3 0 你可以这样做: df['result'] = np.where(
true
或false
更新一列。示例列名称为price
和result
,如果price
列的值为promotion
,则结果列应更新为true
或false
请帮我解决这个问题。鉴于此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
假设数据帧如下所示:
price result
0 0 False
1 1 False
2 2 False
3 promotion False
4 3 False
5 promotion False
price result
0 0 False
1 1 False
2 2 False
3 promotion True
4 3 False
5 promotion 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 False
4 3 False
5 promotion False
price result
0 0 False
1 1 False
2 2 False
3 promotion True
4 3 False
5 promotion True
df[result].apply(lambda x:x==提升值)