gpt4 book ai didi

python - 使用平均值填充数据框中缺失的日期

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:27 24 4
gpt4 key购买 nike

我有定期将日期拉入数据框的日期。数据通常格式正确,但有时在其他日期列中有错误数据。

我总是希望有一个经过解析的 9 位数字形式的日期:

(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
(2015, 12, 29, 0, 30, 50, 1, 363, 0)

我应该如何检查和解决这个问题?

我想做的是将不是日期的任何内容替换为基于表示 last_update + 1/2 更新间隔的变量的日期,这样项目就不会被以后的函数过滤掉。

显示的数据是从 feedparser 中发布_解析的。

import pandas as pd
import datetime

# date with ugly data
df_date_ugly = pd.DataFrame({'date': [
(2015, 12, 29, 0, 30, 50, 1, 363, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0),
'None', '',
(2015, 12, 28, 23, 59, 12, 0, 362, 0)
]})

# date is fine
df_date = pd.DataFrame({'date': [
(2015, 12, 29, 0, 30, 50, 1, 363, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0)
]})

Pseudocode
if the original_date is valid
return original_date
else
return substitute_date

最佳答案

import calendar
import numpy as np
import pandas as pd

def tuple_to_timestamp(x):
try:
return calendar.timegm(x) # 1
except (TypeError, ValueError):
return np.nan

df = pd.DataFrame({'orig': [
(2015, 12, 29, 0, 30, 50, 1, 363, 0),
(2015, 12, 28, 23, 59, 12, 0, 362, 0),
'None', '',
(2015, 12, 30, 23, 59, 12, 0, 362, 0)]})

ts = df['orig'].apply(tuple_to_timestamp) # 2
# 0 1451349050
# 1 1451347152
# 2 NaN
# 3 NaN
# 4 1451519952
# Name: orig, dtype: float64

ts = ts.interpolate() # 3
# 0 1451349050
# 1 1451347152
# 2 1451404752
# 3 1451462352
# 4 1451519952
# Name: orig, dtype: float64

df['fixed'] = pd.to_datetime(ts, unit='s') # 4

print(df)

产量

                                    orig               fixed
0 (2015, 12, 29, 0, 30, 50, 1, 363, 0) 2015-12-29 00:30:50
1 (2015, 12, 28, 23, 59, 12, 0, 362, 0) 2015-12-28 23:59:12
2 None 2015-12-29 15:59:12
3 2015-12-30 07:59:12
4 (2015, 12, 30, 23, 59, 12, 0, 362, 0) 2015-12-30 23:59:12

解释:

  1. calendar.timegm 将每个时间元组转换为时间戳。不像time.mktime,它将时间元组解释为 UTC 时间,而不是本地时间。

  2. applydf['orig'] 的每一行调用 tuple_to_timestamp

  3. 时间戳的优点在于它们是数字,因此您可以使用诸如 Series.interpolate 之类的数值方法用插值填充 NaN值。请注意,这两个 NaN 不会用相同的插值填充;它们的值根据 ts.index 给定的位置进行线性插值。

  4. pd.to_datetime 将时间戳转换为日期。

关于python - 使用平均值填充数据框中缺失的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com