Pandas: expand the series index so that it contains all the values ​​in the range

I have a pandas series that looks like this:

>>> x.sort_index()
2       1
5       2
6       3
8       4

I want to populate this series so that the “missing” rows of indices are represented, populating the data values ​​with 0.

So, when I list a new series, it looks like this:

>>> z.sort_index()
1       0
2       1
3       0
4       0
5       2
6       3
7       0
8       4

I tried to create a series of "dummy"

>>> y = pd.Series([0 for i in range(0,8)])
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0

And then combining them together, but the results also:

>>> pd.concat([x,z],axis=0)
2    1
5    2
6    3
8    4
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0

or

>>> pd.concat([x,z],axis=1)
    0   1
0 NaN   0
1 NaN   0
2   1   0
3 NaN   0
4 NaN   0
5   2   0
6   3   0
7 NaN   0
8   4 NaN

None of them are my target structure mentioned above.

I could try to do some arithmetic according to axis = 1 and take the sum of columns 1 and 2, but I'm looking for a tidier single-line version of this - does such an operation fill / clear the index, and if so, what is it?

+4
source share
2

reindex. , ( ), :

In [64]: x = pd.Series([1,2,3,4], index=[2,5,6,8])

In [65]: x
Out[65]:
2    1
5    2
6    3
8    4
dtype: int64

In [66]: x.reindex(range(9), fill_value=0)
Out[66]:
0    0
1    0
2    1
3    0
4    0
5    2
6    3
7    0
8    4
dtype: int64
+8

- , , , , .

- , , :

>>> x.combine_first(y)
0    0
1    0
2    1
3    0
4    0
5    2
6    3
7    0
8    4
dtype: float64

N.B. ,

>>> y = pd.Series([0 for i in range(0,8)])
0