-----------------------------------------------------------------------------------------------------------------------------------------------
#重新设置索引,多出的索引数据填充
#重新设置索引,多出的索引数据填充 import pandas as pd s=pd.Series([11, 22, 33], index=[1,2,3]) print(s) #重新设置索引 print(s.reindex(range(1, 6))) #多出来两为NaN #使用0进行填充 print(s.reindex(range(1,6),fill_value=0)) #向前填充和向后填充 print(s.reindex(range(1,6),method='ffill')) #向前填充 print(s.reindex(range(1,6),method='bfill')) #向后填充
1 11 2 22 3 33 dtype: int64 1 11.0 2 22.0 3 33.0 4 NaN 5 NaN dtype: float64 1 11 2 22 3 33 4 0 5 0 dtype: int64 1 11 2 22 3 33 4 33 5 33 dtype: int64 1 11.0 2 22.0 3 33.0 4 NaN 5 NaN dtype: float64
#DataFrame对象重新设置索引 import pandas as pd pd.set_option ('display.unicode.east_asian_width',True) data=[[90,100,90], [100,39,89], [49,79,87]] index=['msb1001','msb1002','msb1003'] columns=['数学','语文','英语'] df=pd.DataFrame (data=data,index=index,columns=columns) print(df) #重新设置行索引 print (df. reindex(['msb1001', 'msb1002', 'msb1003', 'msb1004', 'msb1005' ])) #重新设置列索引 print (df.reindex (columns=['数学','语文','英语','政治','历史'])) #重新设置行索引和列索引 print (df. reindex(index=['msb1001', 'msb1002', 'msb1003', 'msb1004', 'msb1005' ],columns=['数学','语文','英语','政治','历史']))
数学 语文 英语 msb1001 90 100 90 msb1002 100 39 89 msb1003 49 79 87 数学 语文 英语 msb1001 90.0 100.0 90.0 msb1002 100.0 39.0 89.0 msb1003 49.0 79.0 87.0 msb1004 NaN NaN NaN msb1005 NaN NaN NaN 数学 语文 英语 政治 历史 msb1001 90 100 90 NaN NaN msb1002 100 39 89 NaN NaN msb1003 49 79 87 NaN NaN 数学 语文 英语 政治 历史 msb1001 90.0 100.0 90.0 NaN NaN msb1002 100.0 39.0 89.0 NaN NaN msb1003 49.0 79.0 87.0 NaN NaN msb1004 NaN NaN NaN NaN NaN msb1005 NaN NaN NaN NaN NaN