Tag Archives: ReIndex

Reintex index of pandas

Convention:

import pandas as pd
import numpy as np

ReIndex reindexes
Reindex () is an important method of the Pandas object, which creates a new object with a new index.
I. Re-index Series objects

se1=pd.Series([1,7,3,9],index=['d','c','a','f'])
se1

Code results:

d    1
c    7
a    3
f    9
dtype: int64

Calling reindex will reorder the missing values and fill them with NaN.

se2=se1.reindex(['a','b','c','d','e','f'])
se2

Code results:

a    3.0
b    NaN
c    7.0
d    1.0
e    NaN
f    9.0
dtype: float64

When passing in method= “” select interpolation processing mode when reindexing:
Method = ‘ffill’ or ‘pad forward filling
Method = ‘bfill’ or ‘backfill’

se3=pd.Series(['blue','red','black'],index=[0,2,4])
se4=se3.reindex(range(6),method='ffill')
se4

Code results:

0     blue
1     blue
2      red
3      red
4    black
5    black
dtype: object

Second, reindex the DataFrame object
For a DataFrame object, reIndex can modify the row index and column index.

df1=pd.DataFrame(np.arange(9).reshape(3,3),index=['a','c','d'],columns=['one','two','four'])
df1

Code results:

one two four
a 0 1 2
c 3 4 5
d 6 7 8

Reordering the row index by default
Passing in only one sequence does not rearrange the index of the sequence

df1.reindex(['a','b','c','d'])

Code results:

The

c 3.0

one

two

four

a 0.0

1.0

2.0

b

NaN

NaN

NaN

4.0

5.0

d 6.0

7.0

8.0

df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'])

Code results:

one

two

three

four

a 0.0

1.0

NaN

2.0

b

NaN

NaN

NaN

NaN

c 3.0

4.0

NaN

5.0

d 6.0

7.0

NaN

8.0

Pass in fill_value=n and replace the missing value with n:

df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'],fill_value=100)

Code results:

one two three four
a 0 1 100 2
b 100 100 100 100
c 3 4 100 5
d 6 7 100 8

Thanks for your browsing,
hope my efforts can help you,
encourage!