Pandas 熊猫:如果循环中满足条件,则更新值
如果满足条件,我必须更新数据帧列。但是有多个条件和多个值需要更新。因此,我想在一个循环中完成它 数据帧类似于:Pandas 熊猫:如果循环中满足条件,则更新值,pandas,for-loop,conditional-statements,Pandas,For Loop,Conditional Statements,如果满足条件,我必须更新数据帧列。但是有多个条件和多个值需要更新。因此,我想在一个循环中完成它 数据帧类似于: mode car1 car2 bus1 bus2 car1 10 20 5 2 car2 11 22 3 1 bus1 4 4 2 2 bus2 3 4 3 5 targets = ['car1', 'car2', 'bus1', 'bus2'] for target
mode car1 car2 bus1 bus2
car1 10 20 5 2
car2 11 22 3 1
bus1 4 4 2 2
bus2 3 4 3 5
targets = ['car1', 'car2', 'bus1', 'bus2']
for target in targets:
df.loc[(df.mode==f'target'),'value']=df.[target]
我意识到数据结构有点奇怪,但让我们继续这个。如果mode显示为car1,我希望新列的值与列car1中的值相同。等等
我的代码如下:
mode car1 car2 bus1 bus2
car1 10 20 5 2
car2 11 22 3 1
bus1 4 4 2 2
bus2 3 4 3 5
targets = ['car1', 'car2', 'bus1', 'bus2']
for target in targets:
df.loc[(df.mode==f'target'),'value']=df.[target]
这是可行的,但每次都会用NaN替换不满足条件的行。因此,我只得到一个新的value列,该列包含bus2行中bus2的值,但包含所有其他行中的NaNs
在斯塔塔,我会写:
gen value = .
foreach x in car1 car2 bus1 bus2 {
replace value = `x' if mode=="`x'"
}
在Python中寻找类似的代码 这应该有效:
df['newcol'] = 0
for key, item in df.iterrows():
df['newcol'].iloc[key] = item[item['mode']]
在
pandas
中有lookup
df['newvalue']=df.set_index('mode').lookup(df['mode'],df['mode'])
df
Out[184]:
mode car1 car2 bus1 bus2 newcol newvalue
0 car1 10 20 5 2 10 10
1 car2 11 22 3 1 22 22
2 bus1 4 4 2 2 2 2
3 bus2 3 4 3 5 5 5