填写熊猫中每个组的缺失日期和回填值

时间:2019-12-12 07:57:03

标签: python-3.x pandas dataframe

我尝试为year2015~2019中的每个city填充bfill中遗漏的value条。

  city  year  value
0   bj  2017     15
1   bj  2019     17
2   sh  2015     23
3   sh  2016     24
4   sh  2019     16

如何获得这样的预期结果?谢谢。

  city  year  value
0   bj  2015     15
1   bj  2016     15
2   bj  2017     15
3   bj  2018     17
4   bj  2019     17
5   sh  2015     23
6   sh  2016     24
7   sh  2017     16
8   sh  2018     16
9   sh  2019     16

我尝试使用下面的代码创建cityyear对:

rng = pd.date_range('2015', '2019', freq='YS').year
c = df['city'].unique()
mux = pd.MultiIndex.from_product([c, rng], names=['city','year'])
print(mux)

我得到:

MultiIndex([('bj', 2015),
            ('bj', 2016),
            ('bj', 2017),
            ('bj', 2018),
            ('bj', 2019),
            ('sh', 2015),
            ('sh', 2016),
            ('sh', 2017),
            ('sh', 2018),
            ('sh', 2019)],
           names=['city', 'year'])

2 个答案:

答案 0 :(得分:2)

DataFrame.reindex创建的DaatFrame中使用MultiIndex中的DataFrame.set_index,然后在第一级city中使用GroupBy.bfill

df = df.set_index(['city','year']).reindex(mux).groupby(level=0).bfill().reset_index()
print (df)
  city  year  value
0   bj  2015   15.0
1   bj  2016   15.0
2   bj  2017   15.0
3   bj  2018   17.0
4   bj  2019   17.0
5   sh  2015   23.0
6   sh  2016   24.0
7   sh  2017   16.0
8   sh  2018   16.0
9   sh  2019   16.0

答案 1 :(得分:2)

仅从原始数据开始就没有多索引:

df = pd.DataFrame({'city': {0: 'bj', 1: 'bj', 2: 'sh', 3: 'sh', 4: 'sh'},
                   'year': {0: 2017, 1: 2019, 2: 2015, 3: 2016, 4: 2019},
                   'value': {0: 15, 1: 17, 2: 23, 3: 24, 4: 16}})

print (df.groupby("city").apply(lambda x: x.set_index("year")
       .reindex(range(min(df["year"]),max(df["year"]+1))).bfill())
       .drop("city",axis=1).reset_index())

"""
  city  year  value
0   bj  2015   15.0
1   bj  2016   15.0
2   bj  2017   15.0
3   bj  2018   17.0
4   bj  2019   17.0
5   sh  2015   23.0
6   sh  2016   24.0
7   sh  2017   16.0
8   sh  2018   16.0
9   sh  2019   16.0
"""