Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 293
sailestim Avatar asked Aug 10 '18 13:08

sailestim


People also ask

How do you update a column based on conditions in pandas?

loc to change values in a DataFrame column based on a condition. Call pandas. DataFrame. loc [condition, column_label] = new_value to change the value in the column named column_name to value in each row for which condition is True .

How replace column values in pandas based on multiple conditions?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.

How get value from another column in pandas?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression. The blow example returns a Courses column where the Fee column value matches with 25000.


1 Answers

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
like image 186
Rushabh Mehta Avatar answered Oct 07 '22 17:10

Rushabh Mehta