我建议通过to_datetime 将dates 转换为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)
或通过strings 进行比较:
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