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