【问题标题】:Group by month in a Pandas dataframe when there is no year in the datetime object当 datetime 对象中没有年份时,在 Pandas 数据框中按月分组
【发布时间】:2021-09-12 00:13:02
【问题描述】:

我有一个带有 date_time 字段(对象)的大型数据集,格式如下:01/01 01:00:00(月/日时:分:秒)。没有年份。我希望能够在 Pandas 数据框中按月对数据集进行分组。

无论我尝试什么,我都会收到错误,例如“在位置 3 解析日期时间字符串“01/01 01:00:00”时出错”或越界错误。我在这里有点新手。我怀疑这是日期时间格式问题,因为没有年份...但我无法弄清楚。

【问题讨论】:

  • 能否将列转换为字符串,然后将年份添加到列中?
  • 是同一年还是需要将年份从 12/31 增加到 1/1 ?

标签: python pandas datetime pandas-groupby


【解决方案1】:

如果你没有一年,你就没有真正的约会。但是你仍然可以按月分组,把它当作一个字符串!

类似的东西应该可以工作:

# create a month string column, called month_str 
# the lambda function just turns the col with the yearless 'dates' into a str 
#    and takes only the first two characters
df['month_str'] = df['datetime'].apply(lambda x: str(x)[0:2])
df.groupby('month_str')

【讨论】:

  • 或:df.groupby(df['date_time'].str[:2])
  • get_monthly["Month"] = get_monthly["Date_Time"].apply(lambda x: str(x)[0:3]) 这行得通!感谢您的建议。
猜你喜欢
  • 2019-04-17
  • 2019-04-15
  • 2017-11-05
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2019-09-21
  • 2021-10-16
相关资源
最近更新 更多