【问题标题】:Pandas "to_datetime" not accepting series熊猫“to_datetime”不接受系列
【发布时间】:2020-11-17 12:18:35
【问题描述】:

我是 pandas 的新手,我正在尝试将日期格式为“%d %B”(1 月 1 日、1 月 2 日 ....)的字符串列转换为日期时间对象,列的类型是<class 'pandas.core.series.Series'> 。 如果我在 to_datetime 方法中传入这个系列,比如

print(pd.to_datetime(data_file['Date'], format='%d %B', errors="coerce"))

所有条目都返回NaT,它应该返回日期时间对象

我检查了文档,它说它接受一个 Series 对象。

有什么办法解决这个问题?

编辑 1: 这是我正在使用的数据的头部:

           Date  Daily Confirmed
0   30 January                 1
1   31 January                 0
2  01 February                 0
3  02 February                 1
4  03 February                 1

编辑2:这里是数据的信息

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 179 entries, 0 to 178
Data columns (total 2 columns):
 #   Column           Non-Null Count  Dtype 
---  ------           --------------  ----- 
 0   Date             179 non-null    object
 1   Daily Confirmed  179 non-null    int64 
dtypes: int64(1), object(1)
memory usage: 2.2+ KB

【问题讨论】:

  • 可能是 format='%d %B' 不匹配
  • 匹配,如果 id 为 print(pd.to_datetime(["01 January"], format='%d %B', errors="coerce")),则返回一个日期时间对象
  • 好的,你能分享一些示例数据吗?
  • 我已将数据添加到帖子中(所有日期也是字符串)
  • 它不能转换为没有年份的日期时间。

标签: python pandas dataframe time-series


【解决方案1】:

如果我理解正确,您可能会遇到此问题,因为此列中的日期周围有空格。要解决它,请在to_datetime 之前使用strip。下面是一段代码:

df = pd.DataFrame({'Date': 
                   ['30 January ', '31 January ', ' 01 February ', '02 February', 
                    '03 February'], 'Daily Confirmed': [1, 0, 0, 1, 1]})

pd.to_datetime(df.Date.str.strip(), format = "%d %B")

输出是:

0   1900-01-30
1   1900-01-31
2   1900-02-01
...

【讨论】:

  • 谢谢!这解决了它。实际上我检查了一些日期有空格而不是其他日期,所以它不统一。一个快速的正则表达式解决了这个问题。
【解决方案2】:
import pandas as pd 
dic =  {"Date": ["30 January", "31 January", "01 February", ] ,  "Daily Confirmed":[0,1,0]}
df =pd.DataFrame(dic)
df['date1'] = pd.to_datetime(df['Date'].astype(str), format='%d %B')
df

默认情况下,它包含 1900 年。因为您没有在 Dataframe 上提供年份 输出:

    Date       Daily Confirmed  date1
0   30 January      0          1900-01-30
1   31 January      1          1900-01-31
2   01 February     0          1900-02-01

如果您不希望年份作为日期的前缀。请添加以下代码:

df['date2']=df['date1'].dt.strftime('%d-%m')
df
    Date       Daily Confirmed  date1         date2
0   30 January      0          1900-01-30     30-1
1   31 January      1          1900-01-31     31-1
2   01 February     0          1900-02-01     01-2

谢谢

【讨论】:

    【解决方案3】:

    你可以试试这个:

    from datetime import datetime
    
    df['datetime'] = df['date'].apply(lambda x: datetime.strptime(x, "%d %B"))
    

    apply() 允许您串联使用python函数,这里您可能需要指定年份,否则默认年份(1900)将被设置为默认值。

    祝你好运

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 1970-01-01
      • 2018-11-12
      • 2018-06-05
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多