【问题标题】:Match datetime YYYY-MM-DD object in pandas dataframe匹配熊猫数据框中的日期时间 YYYY-MM-DD 对象
【发布时间】:2020-09-12 01:07:54
【问题描述】:

我有一个pandas DataFrame 的形式:

    id     amount           birth
0   4      78.0      1980-02-02 00:00:00
1   5      24.0      1989-03-03 00:00:00
2   6      49.5      2014-01-01 00:00:00
3   7      34.0      2014-01-01 00:00:00
4   8      49.5      2014-01-01 00:00:00

我只对dataframebirth 列中的年、月和日感兴趣。我试图利用来自pandasPython datetime,但它导致了一个错误:

OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1054-02-07 00:00:00

birth 列是 object dtype。

我的猜测是日期不正确。我想将参数errors="coerce" 传递给to_datetime 方法,因为每个项目都很重要,我只需要YYYY-MM-DD

我试图利用来自pandasregex

df["birth"].str.find("(\d{4})-(\d{2})-(\d{2})")

但这会返回NANs。我该如何解决这个问题?

谢谢

【问题讨论】:

  • 您可能需要在处理 df['birth'] 之前将其转换为不同的数据类型。你能发布df.dtypes的输出吗?
  • df['Year'] = df['birth'].astype(str).str.extract(r'^(\d{4})', expand=False) / df['Month'] = df['birth'].astype(str).str.extract(r'-(\d{1,2})-', expand=False) / df['Day'] = df['birth'].astype(str).str.extract(r'^.*-(\d{1,2})', expand=False)
  • 那么当我说您只想返回一个包含YYYY-MM-DD 格式的所有值的列表时,我是否正确阅读?
  • 没错!这就是我需要的。

标签: python python-3.x regex pandas dataframe


【解决方案1】:

由于无法转换为日期时间,您可以通过第一个空格使用split,然后选择第一个值:

df['birth'] = df['birth'].str.split().str[0]

然后在必要时转换为句点。

Representing out-of-bounds spans.

print (df)
   id  amount                birth
0   4    78.0  1980-02-02 00:00:00
1   5    24.0  1989-03-03 00:00:00
2   6    49.5  2014-01-01 00:00:00
3   7    34.0  2014-01-01 00:00:00
4   8    49.5     0-01-01 00:00:00

def to_per(x):
    splitted = x.split('-')
    return pd.Period(year=int(splitted[0]), 
                     month=int(splitted[1]), 
                     day=int(splitted[2]), freq='D')

df['birth'] = df['birth'].str.split().str[0].apply(to_per)

print (df)
   id  amount       birth
0   4    78.0  1980-02-02
1   5    24.0  1989-03-03
2   6    49.5  2014-01-01
3   7    34.0  2014-01-01
4   8    49.5  0000-01-01

【讨论】:

  • 我收到一个错误:DateParseError: year 0 is out of range 并且没有句点返回NANs
  • .apply(pd.Period)
  • 出生列是object dtype。但由于某些原因,我收到此错误:AttributeError: 'float' object has no attribute 'split' 但链接 astype(str) 会出现另一个错误:ValueError: invalid literal for int() with base 10: 'nan'
  • @Pythonista - 文件中是否可以共享列? df['birth'].to_csv('dates.csv', index=False) ?因为这似乎是一些与数据相关的问题。
猜你喜欢
  • 2019-02-16
  • 2018-03-31
  • 2021-12-17
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 2018-01-13
  • 2013-10-19
相关资源
最近更新 更多