Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally update DataFrame column in Pandas

Tags:

python

pandas

With this DataFrame, how can I conditionally set rating to 0 when line_race is equal to zero?

    line_track  line_race  rating foreign  25        MTH         10     84    False  26        MTH          6     88    False  27        TAM          5     87    False  28         GP          2     86    False  29         GP          7     59    False  30        LCH          0    103     True  31        LEO          0    125     True  32        YOR          0    126     True  33        ASC          0    124     True 

In other words, what is the proper way on a DataFrame to say if ColumnA = x then ColumnB = y else ColumnB = ColumnB

like image 796
TravisVOX Avatar asked Aug 12 '13 20:08

TravisVOX


People also ask

How do you update a DataFrame column based on another DataFrame?

To update a dataframe value from another dataframe, create a separate DataFrame for a similar row and then we will rest the index of the first DataFrame with the column of the second DataFrame.

How do I change the value of a column in a data frame?

Suppose that you want to replace multiple values with multiple new values for an individual DataFrame column. In that case, you may use this template: df['column name'] = df['column name']. replace(['1st old value', '2nd old value', ...], ['1st new value', '2nd new value', ...])

How do you change a column value in Python?

With the Python iloc() method, it is possible to change or update the value of a row/column by providing the index values of the same. In this example, we have updated the value of the rows 0, 1, 3 and 6 with respect to the first column i.e. 'Num' to 100.


1 Answers

df.loc[df['line_race'] == 0, 'rating'] = 0 
like image 116
Viktor Kerkez Avatar answered Oct 11 '22 04:10

Viktor Kerkez