Advertisements
I have a data like below in a pandas dataframe but there are over 500 columns and for columns 2-500+ I need to divide only the rows where in column 0 the value is ‘dog’ by 100.
0 1 2 3
cat 2019 19.80 96.28
cat 2022 19.50 66.80
dog 2022 21.10 57.70
dog 2021 21.50 42.85
The expected output is below:
0 1 2 3
cat 2019 19.80 96.28
cat 2022 19.50 66.80
dog 2022 0.211 0.577
dog 2021 0.215 0.4285
I have the following code which works to divide it by 100 for those specific rows and columns but it removes columns 0 and 1 and any rows that aren’t ‘dog’.
df=df[df[0].str.contains("dog")].loc[:,2:len(r2.columns)-1].div(100)
How do I keep the full dataframe and apply this division on those specific rows and columns?
>Solution :
Hate it when people post the correct answer in the comments, Imma just post the same thing as I thought as a real answer. Small credit for @mozway cuz’ otherwise I would’ve needed to rummage in my brain how to do so.
df.loc[df[0].str.contains("dog"), 2:] /= 100
Have a good day.