【问题标题】:Datetime comparison using f strings in python在python中使用f字符串进行日期时间比较
【发布时间】:2021-12-21 23:56:29
【问题描述】:

考虑以下数据框

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])
Y['Date'] = pd.to_datetime(Y['Date'])

现在考虑以下代码 sn-p,其中我尝试打印在“日期”列上过滤的数据帧的切片。但是,它会打印一个空数据框

for date in set(Y['Date']):
    print(Y.query(f'Date == {date.date()}'))

本质上,我想过滤“日期”列上的数据框,并在循环中对其进行一些处理。我如何做到这一点?

【问题讨论】:

  • 你想做什么以及如何过滤日期?

标签: python pandas string f-string


【解决方案1】:

需要通过以下查询命令访问日期:

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])
for date in set(Y['Date']):
    print(Y.query('Date == @date'))

【讨论】:

  • 定义“date_to_be_queried”需要什么?
  • 它是实现的产物,谢谢。
【解决方案2】:

使用"",因为f-strings删除了原始""并引发错误:

Y = pd.DataFrame([("2021-10-11","john"),("2021-10-12","wick")],columns = ['Date','Name'])

Y['Date'] = pd.to_datetime(Y['Date'])


for date in set(Y['Date']):
    print(Y.query(f'Date == "{date}"'))

【讨论】:

  • 为什么 repr 返回一个可比较的字符串表示?只是好奇。
  • @dineshdileep - 再次检查并通过this更改解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 2022-11-21
  • 2016-12-02
  • 2022-01-16
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多