简体   繁体   中英

Python creating a new dataframe with list of unique dates as index

I have dateframe with index as df.index =

2016-08-01 06:45:00    
2016-08-01 07:00:00    
2016-08-01 07:15:00    
.
.
2018-03-28 11:30:00    
2018-03-28 11:45:00    
2018-03-28 12:00:00  

I want to create a new dataframe that it will have only unique dates as

new_df.index =

2016-08-01
2016-08-02
.
.
2018-03-28
2018-03-29

So, how to create a new dataframe with unique dates as index?

There is a build-in collection set in Python, that have only unique elements. You can do something like it:

new_data = sorted(list(set(old_data)))

If you want to crop out time in your datetime lines, you can modify this code with generators:

new_data = sorted(list(set([elem[:10] for elem in old_data])))

Note, that if you have some info linked with your datetimes (like values in dict with datetime keys), you must handle elements removal before doing it.

Since you have not provided any data I will assume it is not important.

Your first DataFrame appears to have a DatetimeIndex and it appears you want to convert it to a PeriodIndex . You can do this to get the unique days with df.resample(rule='D').asfreq() . Docs are here

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