python - 在 Python 数据框中按年度填补空白的最佳方法

标签 python pandas date dataframe

所有,我是 Python 的新手,并且遇到以下问题。我有一个 DF 作为:

ipdb> DF

    asofdate  port_id
1 2010-01-01       76
2 2010-04-01       43
3 2011-02-01       76
4 2013-01-02       93
5 2017-02-01       43

对于年度差距,比如 2012、2014、2015 和 2016,我想使用每个缺失年份的新年日期和前一年的 port_id 来填补差距。理想情况下,我想:

ipdb> DF

    asofdate  port_id
1 2010-01-01       76
2 2010-04-01       43
3 2011-02-01       76
4 2012-01-01       76
5 2013-01-02       93
6 2014-01-01       93
7 2015-01-01       93
8 2016-01-01       93
9 2017-02-01       43

我尝试了多种方法,但仍然无济于事。一些专家可以告诉我如何解决这个问题吗?提前致谢!

最佳答案

您可以使用 set.differencerange 来查找缺失的日期,然后附加一个数据框:

# convert to datetime if not already converted
df['asofdate'] = pd.to_datetime(df['asofdate'])

# calculate missing years
years = df['asofdate'].dt.year
missing = set(range(years.min(), years.max())) - set(years)

# append dataframe, sort and front-fill
df = df.append(pd.DataFrame({'asofdate': pd.to_datetime(list(missing), format='%Y')}))\
       .sort_values('asofdate')\
       .ffill()

print(df)

    asofdate  port_id
1 2010-01-01     76.0
2 2010-04-01     43.0
3 2011-02-01     76.0
1 2012-01-01     76.0
4 2013-01-02     93.0
2 2014-01-01     93.0
3 2015-01-01     93.0
0 2016-01-01     93.0
5 2017-02-01     43.0

关于python - 在 Python 数据框中按年度填补空白的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526818/

相关文章:

python - 将字符串从 pandas 数据帧转换为列表 - python

python - Pandas :删除重复但连续的行并将第一行保留在组中

javascript - 将字符串 (3-11-2012) 替换为其他日期格式 (2012 年 11 月 3 日)

php - 使用时间戳或日期列类型将出生日期保存到 MYSQL DB

python - 调试 Django 表单验证错误

python - 尝试实现导入-> Debug模式模块

python - Objective-C 中的简洁字符串切片

python - 在 Python 中重构数据框

python - Pandas:添加满足条件的元素的渐进计数列

javascript - 如何在javascript中从字符串创建日期对象