我试图遍历我创建的某些日期,但出现错误。这是代码:
q3_2018 = datetime.date(2018,9,30)
q4_2018 = datetime.date(2018,12,31)
q1_2019 = datetime.date(2019,3,31)
q2_2019 = datetime.date(2018,6,30)
dates = [q3_2018, q4_2018,q1_2019,q2_2019]
values = []
for d in dates:
v = fin[fin['Date of Completion 1 payment']<d]['1st payment amount:\n(70%)'].sum()
values.append(v)
其中fin ['完成日期1付款日期']是带有付款日期的熊猫列,而fin ['第一付款金额:\ n(70%)']是带有付款金额的熊猫列。
我收到以下错误
TypeError:键入对象2018-09-30
哪里出问题了?
答案 0 :(得分:0)
我建议将to_datetime
的date
转换为datetimes
,然后将DataFrame.loc
用于选择列:
dates = pd.to_datetime([q3_2018, q4_2018,q1_2019,q2_2019])
print (dates)
DatetimeIndex(['2018-09-30', '2018-12-31', '2019-03-31', '2018-06-30'],
dtype='datetime64[ns]', freq=None)
或按string
s进行比较:
dates = pd.to_datetime([q3_2018, q4_2018,q1_2019,q2_2019]).strftime('%Y-%m-%d')
print (dates)
Index(['2018-09-30', '2018-12-31', '2019-03-31', '2018-06-30'], dtype='object')
或者:
dates = ['2018-09-30', '2018-12-31' '2019-03-31','2018-06-30']
values = []
for d in dates:
v = fin.loc[fin['Date of Completion 1 payment']<d, '1st payment amount:\n(70%)'].sum()
values.append(v)
列表理解解决方案:
values = [fin.loc[fin['Date of Completion 1 payment']<d, '1st payment amount:\n(70%)'].sum()
for d in dates]
或升级到最新版本的熊猫以与日期进行比较,请选中here:
# 0.22.0... Silently coerce the datetime.date
>>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1)
0 True
1 False
dtype: bool
# 0.23.0... Do not coerce the datetime.date
>>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1)
0 False
1 False
dtype: bool
# 0.23.1... Coerce the datetime.date with a warning
>>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1)
/bin/python:1: FutureWarning: Comparing Series of datetimes with 'datetime.date'. Currently, the
'datetime.date' is coerced to a datetime. In the future pandas will
not coerce, and the values not compare equal to the 'datetime.date'.
To retain the current behavior, convert the 'datetime.date' to a
datetime with 'pd.Timestamp'.
#!/bin/python3
0 True
1 False
dtype: bool