在Python datafram中通过年度日期填补空白的最佳方法

2024-10-17 02:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我是Python的新手,我被下面的问题困住了。我有一个DF作为:

ipdb>;数据框

    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年,我想用缺失年份的新年日期和上一年的港口id来填补缺口。理想情况下,我想:

ipdb>;数据框

    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

我尝试了多种方法,但仍然没有结果。有专家能告诉我怎么做吗?提前多谢!你知道吗


Tags: 数据方法gtiddfport情况年份
2条回答

您可以使用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

我将创建一个helper数据框,其中包含所有的年份开始日期,然后过滤出与df中年份匹配的年份,最后将它们合并在一起:

# First make sure it is proper datetime
df['asofdate'] = pd.to_datetime(df.asofdate)

# Create your temporary dataframe of year start dates
helper = pd.DataFrame({'asofdate':pd.date_range(df.asofdate.min(), df.asofdate.max(), freq='YS')})

# Filter out the rows where the year is already in df
helper = helper[~helper.asofdate.dt.year.isin(df.asofdate.dt.year)]

# Merge back in to df, sort, and forward fill
new_df = df.merge(helper, how='outer').sort_values('asofdate').ffill()

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

相关问题 更多 >