Pandas:如果criteri

2024-04-29 02:53:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框:

   A B

1: 0 1
2: 0 0 
3: 1 1
4: 0 1
5: 1 0

如果列A的值等于0,我想用列B的值更新数据帧的每个列A的值。

我要获取的数据帧:

   A B

1: 1 1
2: 0 0 
3: 1 1
4: 1 1
5: 1 0

我已经试过这个密码了

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().


Tags: ofthe数据lambda密码dfifis
3条回答

可以使用掩码执行此操作:

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

编辑: 好吧,这实际上是一个无效的解决方案:

%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)

因此,感谢零这个有效的解决方案与np.where!

使用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
df['A'] = df.apply(lambda x: x['B'] if x['A']==0 else x['A'], axis=1)

输出

    A  B
1:  1  1
2:  0  0
3:  1  1
4:  1  1
5:  1  0

相关问题 更多 >