Reputation: 267
I have a pd.DataFrame
which has datetime64
type of index. I'd like to concatenate a pd.Series
column to it and map it to the index.
However, my pd.Series
has an object
type of dates, while my pd.DataFrame
has a datetime64
type of dates.
I tried converting the pd.Series
index to datetime
like so.
This is how the pd.Series
looks like :
west_index[1:5]
Out[40]:
WEST
Exchange Date
2005-01-05 -0.7466
2005-01-06 NaN
2005-01-07 0.3401
2005-01-10 -0.0688
I did:
a = [datetime.strptime(_, '%Y-%m-%d') for _ in west_index.index]
west_index.set_index(a, inplace=True)
When I try to concatenate to my main pd.DataFrame
, which looks like this:
log_r[500:505]
Out[42]:
BELEX15 BET BUX ... STOXX50 WIG20
Exchange Date ...
2006-12-08 0.131916 1.717272 -0.983922 ... 0.090416 -0.436533
2006-12-11 0.191401 -0.645286 1.158256 ... 0.576408 -0.086710
2006-12-12 -0.190785 -0.764530 0.753001 ... 0.396716 -0.684809
2006-12-13 -0.521898 0.726442 -1.459122 ... 0.629700 0.202408
2006-12-14 0.877326 -0.707257 1.099898 ... 0.718143 0.722291
log_r = pd.concat([log_r,west_index], axis=1)
I get an error
KeyError: datetime.datetime(2005, 1, 4, 0, 0)
Upvotes: 0
Views: 103
Reputation: 862406
I think better is convert log_r.index
or west_index.index
to datetimes for datetimes in both indexes by to_datetime
:
#check it
print (west_index.index.dtype)
print (log_r.index.dtype)
west_index.index = pd.to_datetime(west_index.index)
log_r.index = pd.to_datetime(log_r.index)
log_r = pd.concat([log_r, west_index], axis=1)
Upvotes: 1