简体   繁体   中英

Replace values in Pandas DataFrame with a DateTime Index based on a list of dates

I have a dataframe of values and a list of dates. Eg,

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. Eg,

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...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM