pyspark.pandas.Series.reindex ¶
-
Series.
reindex
( index : Optional [ Any ] = None , fill_value : Optional [ Any ] = None ) → pyspark.pandas.series.Series [source] ¶ -
将系列数据对齐到新的索引,并可选地填充逻辑,将NA/NaN放置在之前索引中没有值的位置。生成一个新对象。
- Parameters
-
- index: array-like, optional
-
新的标签/索引应符合的要求,应使用关键字指定。 最好使用Index对象以避免数据重复
- fill_value scalar, default np.NaN
-
用于缺失值的值。默认为 NaN,但可以是任何“兼容”的值。
- Returns
-
- Series with changed index.
另请参阅
-
Series.reset_index
-
删除行标签或将它们移动到新列。
示例
创建一个包含一些虚构数据的序列。
>>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] >>> ser = ps.Series([200, 200, 404, 404, 301], ... index=index, name='http_status') >>> ser Firefox 200 Chrome 200 Safari 404 IE10 404 Konqueror 301 Name: http_status, dtype: int64
创建一个新索引并重新索引序列。默认情况下,新索引中没有对应记录的值将被分配为
NaN
。>>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', ... 'Chrome'] >>> ser.reindex(new_index).sort_index() Chrome 200.0 Comodo Dragon NaN IE10 404.0 Iceweasel NaN Safari 404.0 Name: http_status, dtype: float64
我们可以通过传递一个值给关键字
fill_value
来填充缺失的值。>>> ser.reindex(new_index, fill_value=0).sort_index() Chrome 200 Comodo Dragon 0 IE10 404 Iceweasel 0 Safari 404 Name: http_status, dtype: int64
为了进一步说明
reindex
中的填充功能,我们将创建一个具有单调递增索引的Series(例如,一系列日期)。>>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') >>> ser2 = ps.Series([100, 101, np.nan, 100, 89, 88], ... name='prices', index=date_index) >>> ser2.sort_index() 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 Name: prices, dtype: float64
假设我们决定将系列扩展到涵盖更广泛的日期范围。
>>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D') >>> ser2.reindex(date_index2).sort_index() 2009-12-29 NaN 2009-12-30 NaN 2009-12-31 NaN 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN Name: prices, dtype: float64