问题
There are so many questions that revolve around converting dates to a datetimeindex. I personally need a datetimeindex to work with the Calmap package that requires the datetimeindex. After following many stackoverflow guides, I haven't been able to change my date fields to a datetimeindex. Here are the following steps I took.
import numpy as np
import pandas as pd
##I also attempted to add parse_dates=["Date'] and Index["Date"] to the pd.read_csv()
main_data = pd.read_csv('newoutput2.csv', delimiter=",", encoding='cp1252')
main_data = main_data.set_index(pd.to_datetime(main_data["Date"], format = "%m/%d/%y"))
import calmap
events = pd.Series(main_data.index)
calmap.yearplot(events, year=2020)
##When I run events[0] the output is
##Timestamp('2020-10-05 00:00:00')
The error I receive after running that code is
python\python38-32\lib\site-packages\calmap\__init__.py in yearplot(data, year, how, vmin, vmax, cmap, fillcolor, linewidth, linecolor, daylabels, dayticks, monthlabels, monthticks, ax, **kwargs)
141 # Sample by day.
142 if _pandas_18:
--> 143 by_day = data.resample("D").agg(how)
144 else:
145 by_day = data.resample("D", how=how)
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
No matter the format I follow, it never seems to create a datetimeindex from the data.
The data is here
The original data
Name Time Date
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
FName LName 12:00PM 10/5/20
If I print main_data, it appears like this
Name Time Date
Date
2020-10-05 FName LName 12:00:00 10/5/20
2020-10-05 FName LName 12:00:00 10/5/20
2020-10-05 FName LName 12:00:00 10/5/20
2020-10-05 FName LName 12:00:00 10/5/20
2020-10-05 FName LName 12:00:00 10/5/20
回答1:
Try concat Date and Time before setting index. Use df.column.str.cat(colum1, sep=' ')
print(df)
Name Time Date
0 FName LName 12:00PM 10/5/20
1 FName LName 12:00PM 10/5/20
2 FName LName 12:00PM 10/5/20
3 FName LName 12:00PM 10/5/20
4 FName LName 12:00PM 10/5/20
5 FName LName 12:00PM 10/5/20
6 FName LName 12:00PM 10/5/20
df['datetime']=pd.to_datetime(df['Date'].str.cat(df.Time, sep=' '))
df.set_index(df['datetime'], inplace=True)
print(df)
Name Time Date datetime
datetime
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00 FName LName 12:00PM 10/5/20 2020-10-05 12:00:00
来源:https://stackoverflow.com/questions/64324891/converting-a-datetime-column-to-a-datetimeindex-in-pandas