Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing value related to a specific date in df?

I have a df like as follows

          Date               Flow
0   1981-01-01  103.432860
1   1981-01-02  102.982800
2   1981-01-03  102.121150
3   1981-01-04  100.92662
...     ....
xx      2020-12-31      150.123

I need to replace the value of flow for every 1st of january as 0.00

df['month'] = df['Date'].dt.month_name()
df['dom']= df['Date'].dt.day

for ind in df.index: 
    df.loc[(df['month'] == 'January') & (df['dom'] == '01'), 'Flow'] = 0

df.head()
Results:
          Date            Flow           month         dom
0   1981-01-01  103.432860  January     1
1   1981-01-02  102.982800  January         2
2   1981-01-03  102.121150  January         3
3   1981-01-04  100.926620  January         4

It’s not working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use an int rather than a string

As MaddDMo pointed out, the reason you code is failing is because you are filtering by df["dom"] == "01" instead of df["dom"] == 0. Because the dom is expressed in integers rather than strings, it is failing to match any columns.

A suggestion

Rather than looping through each line of the dataframe, select just the lines you want to change using loc.

df.loc[(df["month"] == "January") & (df["dom"] == 1), "Flow"] = 0

Note that you need to encase each filter in parentheses to allow for column logic, as you have done.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading