How to replace a column conditionally in Pandas?

Asked

Viewed 53 times

0

I have a dataframe in Pandas and need to replace the value in the column semana conditionally. Where the value is 53, I want to replace with 1.

cod; semana;
A; 53;
A; 1;
A; 1;
A; 2;
B; 53;
B; 1;
B; 1;
B; 2;

That’s what I tried, but to no avail:

df = pd.read_csv("file.csv", encoding = "utf-8", delimiter = ";")

for dado in df['semana']:
    if dado == 53:
        df['semana'].replace(dado, 1)

1 answer

2

Accuse NAY do for in a dataframe. This would be the last resort as it is not performative at all. See this link

To replace all those equal to 53 by 1, do:

df.loc[df['semana'] == 53, 'semana'] = 1

Example:

Creating Dataframe for Testing

>>> import pandas as pd
>>> df = pd.DataFrame({"a": [1,2,3,4], "semana": [1,2,53,2]})
>>> df
   a  semana
0  1       1
1  2       2
2  3      53
3  4       2

Substituting values

>>> df.loc[df['semana'] == 53, 'semana'] = 1
>>> df
   a  semana
0  1       1
1  2       2
2  3       1
3  4       2
>>>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.