Pandas: update column values from another column if criteria [duplicate]

北城以北 提交于 2020-12-30 08:56:31

问题


I have a DataFrame:

   A B

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

I want to update each item column A of the DataFrame with values of column B if value from column A equals 0.

DataFrame I want to get:

   A B

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

I've already tried this code

df['A'] = df['B'].apply(lambda x: x if df['A'] == 0 else df['A'])

It raise an error :The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().


回答1:


df['A'] = df.apply(lambda x: x['B'] if x['A']==0 else x['A'], axis=1)

Output

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



回答2:


Use 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



回答3:


You can perform this by using a mask:

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

EDIT: Ok this is actually a unefficient solution:

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

So thanks to zero for this efficient solution with np.where!



来源:https://stackoverflow.com/questions/51787247/pandas-update-column-values-from-another-column-if-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!