将缺少系列索引的值与主索引合并

时间:2019-10-08 07:50:47

标签: pandas

说我有一个索引:

i = pd.Index(['apple', 'banana', 'orange'])
print(i)

Index(['apple', 'banana', 'orange'], dtype='object')

现在,我执行一些groupby函数,其结果为p

p = pd.Series({'apple' : 1})
print(p)

apple    1
dtype: int64

如何合并此p系列,然后将fillna(0)与索引i合并以获得:

apple     1
banana    0
orange    0
dtype: int64

有些方法像merge使用df,但是我在想是否可以直接使用Series完成此操作?

1 个答案:

答案 0 :(得分:2)

使用Series.reindex索引值和fill_value=0替换缺失值:

print (p.reindex(i, fill_value=0))
apple     1
banana    0
orange    0
dtype: int64
相关问题