Changing certain values in multiple columns of a pandas DataFrame at once

dbliss :

Suppose I have the following DataFrame:

In [1]: df
Out[1]:
  apple banana cherry
0     0      3   good
1     1      4    bad
2     2      5   good

This works as expected:

In [2]: df['apple'][df.cherry == 'bad'] = np.nan
In [3]: df
Out[3]:
  apple banana cherry
0     0      3   good
1   NaN      4    bad
2     2      5   good

But this doesn't:

In [2]: df[['apple', 'banana']][df.cherry == 'bad'] = np.nan
In [3]: df
Out[3]:
  apple banana cherry
0     0      3   good
1     1      4    bad
2     2      5   good

Why? How can I achieve the conversion of both the 'apple' and 'banana' values without having to write out two lines, as in

In [2]: df['apple'][df.cherry == 'bad'] = np.nan
In [3]: df['banana'][df.cherry == 'bad'] = np.nan
Andy Hayden :

You should use loc and do this without chaining:

In [11]: df.loc[df.cherry == 'bad', ['apple', 'banana']] = np.nan

In [12]: df
Out[12]: 
   apple  banana cherry
0      0       3   good
1    NaN     NaN    bad
2      2       5   good

See the docs on returning a view vs a copy, if you chain the assignment is made to the copy (and thrown away) but if you do it in one loc then pandas cleverly realises you want to assign to the original.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Changing values in multiple columns of a pandas DataFrame using known column values

changing data types of multiple columns at once in python/pandas

Pandas DataFrame stack multiple column values into single column without changing one of the columns

Changing multiple column values at once for a single row in my dataframe

How to collectively set the values of multiple columns for certain selected rows for Pandas dataframe?

Change values in pandas dataframe based on values in certain columns

Pandas DataFrame - Got multiple values for argument 'columns'

Test if there are values shared in multiple columns of a pandas DataFrame

Add multiple columns and values to a pandas dataframe

Sort values of multiple text columns in pandas dataframe

How to change values in multiple pandas dataframe columns?

Replace all 0 values with 1 in dataframe with multiple rows and columns at once

How to get value counts for multiple columns at once in Pandas DataFrame?

How can I pivot a pandas dataframe (timeseries) with multiple columns at once?

Changing values of one column based on the other three columns in pandas dataframe

How to count changing values across various columns - Pandas Dataframe

(Pandas) Set values for multiple columns at once using apply

Python, Pandas: changing form of dataframe, one-to-multiple-columns

Pandas Dataframe: Update values in a certain columns for last n rows

Extract rows where the lists of columns contain certain values in a pandas dataframe

Python/Pandas: replacing certain values in multiple columns of large dataset

Subset pandas dataframe on multiple columns based on values from another dataframe

Pandas update multiple columns at once

Dropping multiple columns in pandas at once

Pandas initialize multiple columns at once

Reorder certain columns in pandas dataframe

Changing the columns in DataFrame with respect to values in other columns

Changing cell values of a pandas dataframe

Changing Values in multiindex pandas dataframe

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive