【问题标题】:Date concatenating in new column in dataframe在数据框中的新列中连接日期
【发布时间】:2020-09-12 20:44:33
【问题描述】:

我有列 date 的数据框,类型为 datetime64[ns]

当我尝试根据日期列创建格式为 MM-DD 的新列日时,只有第一种方法从下面起作用。为什么第二种方法在 pandas 中不起作用?

df['day'] = df['date'].dt.strftime('%m-%d')
df['day2'] = str(df['date'].dt.month) + '-' + str(df['date'].dt.day)

一行结果:

day                                                  01-04
day2     0       1\n1       1\n2       1\n3       1\n4 ...

列的类型

day              object
day2             object

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    解决的问题是如果使用strdf['date'].dt.month 它返回Series,正确的方法是使用Series.astype

    df['day2'] = df['date'].dt.month.astype(str) + '-' + df['date'].dt.day.astype(str)
    

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多