【问题标题】:Looping through dates循环日期
【发布时间】:2018-12-19 06:12:21
【问题描述】:

我正在尝试循环浏览我创建的一些日期,但出现错误。这是代码:

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['Date of Completion 1 payment'] 是带有付款日期的 pandas 列,而 fin['1st payment amount:\n(70%)'] 是带有已支付金额的 pandas 列。

我收到以下错误

TypeError:类型对象 2018-09-30

哪里出错了?

【问题讨论】:

  • 什么是fin.dtypes
  • 第一次付款金额:\n(70%) float64 完成日期 1 付款 datetime64[ns] 最终付款:(30%) float64 完成日期 datetime64[ns]

标签: python pandas loops date datetime


【解决方案1】:

我建议通过to_datetimedates 转换为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

【讨论】:

  • 不确定为什么它返回 axis=self.obj._get_axis_name(axis))) KeyError: 'the label [Date of Completion 1 payment] is not in the [index]' 而该列显然是在索引中(我检查,没有空格问题,列按原样拼写)..
  • @FilippoSebastio - 通过print (df.columns.tolist()) 检查列名,可能是一些编码或尾随空格问题。
  • @FilippoSebastio - 哎呀,我这边打错了,.loc 需要先fin.loc[fin['Date of Completion 1 payment']&lt;d, '1st payment amount:\n(70%)'].sum()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 2020-12-26
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多