我有以下日期时间日期值:
a_date = datetime.date(2018,9,13)
还有带有以下列的熊猫数据框df
:
df['somedates']
0 2010-07-27
1 1999-02-15
2 1997-07-15
3 2012-11-15
4 1999-02-17
5 1999-02-16
6 1999-02-17
7 2012-10-12
8 1999-09-22
9 1998-05-09
10 1998-05-09
Name: somedates, Length: 11, dtype: datetime64[ns]
我可以在Windows计算机上执行以下操作,并且工作正常
df['somedates'] = a_date - df['somedates']
但是在ubuntu上会引发以下错误:
unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date
有人可以指出正确的方向吗?为什么它在Windows上运行而不在Linux上运行?
更多详细信息
print(type(a_date))
<class 'datetime.date'>
print(type(df['somedates']))
<class 'pandas.core.series.Series'>
print(type(df['somedates'][0]))
<class 'pandas._libs.tslib.Timestamp'>
答案 0 :(得分:1)
由于我无法发表评论:
之所以不起作用,是因为您尝试将datetime的datetimes版本与datetime的pythons版本source一起使用。在您遇到的情况下,我将使用pd.to_datetime()将所有内容转换为同一日期时间:
import pandas as pd
import datetime
a_date = datetime.date(2018,9,13) # we can change this to a_date = pd.to_datetime('2018-9-13')
df = pd.DataFrame()
df['somedates'] = ['2010-07-27', '1999-02-15', '1997-07-15','2012-11-15','2012-11-15','1999-02-17']
df['somedates'] = pd.to_datetime(df['somedates'])
df['somedates'] = pd.to_datetime(a_date) - df['somedates'] # if we enact the change above then we can simply do a_date - df['somedates']
display(df)
somedates
0 2970 days
1 7150 days
2 7730 days
3 2128 days
4 2128 days
5 7148 days
我还会看看this