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().
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With