3

I have a dataframe of values and a list of dates. E.g.,

data = pd.DataFrame([1,3,5,7,2,3,9,1,3,8,4,5],index=pd.date_range(start='2017-01-01',periods=12),columns=['values'])

I want to replace the value of a date in the date list with a zero value. E.g.,

date_list = ['2017-01-04', '2017-01-07', '2017-01-10']

I have tried:

data[date_list] == 0

but this yields an error:

KeyError: "None of [['2017-01-04', '2017-01-07', '2017-01-10']] are in the [index]"

Does anyone have an idea of how to solve this? I have a very large dataframe and date list...

2 Answers 2

3

Another way,

In [11]: data[data.index.isin(date_list)] = 0

In [12]: data
Out[12]:
            values
2017-01-01       1
2017-01-02       3
2017-01-03       5
2017-01-04       0
2017-01-05       2
2017-01-06       3
2017-01-07       0
2017-01-08       1
2017-01-09       3
2017-01-10       0
2017-01-11       4
2017-01-12       5
Sign up to request clarification or add additional context in comments.

Comments

2

You need to convert that list to datetime and use the loc indexer:

data.loc[pd.to_datetime(date_list)] = 0

data
Out[19]: 
            values
2017-01-01       1
2017-01-02       3
2017-01-03       5
2017-01-04       0
2017-01-05       2
2017-01-06       3
2017-01-07       0
2017-01-08       1
2017-01-09       3
2017-01-10       0
2017-01-11       4
2017-01-12       5

This works because the DataFrame has only one column. This sets all the columns to zero. But as jezrael pointed out, if you only want to set the values column to zero, you need to specify that:

data.loc[pd.to_datetime(date_list), 'values'] = 0

3 Comments

In my opinion better solution, maybe if need specify columns data.loc[pd.to_datetime(date_list), 'values'] = 0
@jezrael ah yes I do that mistake all the time. Thanks.
No, I think your solution is fine if need replace all columns. It depends of OP ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.