sai*_*tim 8 python lambda pandas
我有一个数据框:
A B
1: 0 1
2: 0 0
3: 1 1
4: 0 1
5: 1 0
Run Code Online (Sandbox Code Playgroud)
如果A列的值等于 0,我想用B 列的值更新DataFrame 的每个项目列 A。
我想获得的数据帧:
A B
1: 1 1
2: 0 0
3: 1 1
4: 1 1
5: 1 0
Run Code Online (Sandbox Code Playgroud)
我已经试过这个代码
df['A'] = df['B'].apply(lambda x: x if df['A'] == 0 else df['A'])
它引发了一个错误:The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Don*_*and 17
df['A'] = df.apply(lambda x: x['B'] if x['A']==0 else x['A'], axis=1)
Run Code Online (Sandbox Code Playgroud)
输出
A B
1: 1 1
2: 0 0
3: 1 1
4: 1 1
5: 1 0
Run Code Online (Sandbox Code Playgroud)
Zer*_*ero 10
用 where
In [348]: df.A = np.where(df.A.eq(0), df.B, df.A)
In [349]: df
Out[349]:
A B
1: 1 1
2: 0 0
3: 1 1
4: 1 1
5: 1 0
Run Code Online (Sandbox Code Playgroud)
您可以使用掩码执行此操作:
df = pd.DataFrame()
df['A'] = [0,0,1,0,1]
df['B'] = [1,0,1,1,0]
mask = (df.A == 0)
df.loc[mask,'A'] = df.loc[mask,'B']
A B
0 1 1
1 0 0
2 1 1
3 1 1
4 1 0
Run Code Online (Sandbox Code Playgroud)
编辑:好的,这实际上是一个低效的解决方案:
%timeit df.loc[mask,'A'] = df.loc[mask,'B']
%timeit df.apply(lambda x: x['B'] if x['A']==0 else x['A'], axis=1)
%timeit np.where(df.A.eq(0), df.B, df.A)
5.52 ms ± 556 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
1.27 ms ± 167 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
796 µs ± 89.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Run Code Online (Sandbox Code Playgroud)
所以感谢零为 np.where 提供了这个有效的解决方案!