pyspark.pandas.DataFrame.reindex ¶
-
DataFrame.
reindex
( labels : Optional [ Sequence [ Any ] ] = None , index : Union[Index, Sequence[Any], None] = None , columns : Union[pandas.core.indexes.base.Index, Sequence[Any], None] = None , axis : Union[int, str, None] = None , copy : Optional [ bool ] = True , fill_value : Optional [ Any ] = None ) → DataFrame [source] ¶ -
使DataFrame符合新索引,并可选择填充逻辑,将NA/NaN放置在没有先前索引值的位置。除非新索引等同于当前索引且
copy=False
,否则将生成一个新对象。- Parameters
-
- labels: array-like, optional
-
新的标签/索引,以使由‘axis’指定的轴符合。
- index, columns: array-like, optional
-
新的标签/索引应符合的要求,应使用关键字指定。 最好使用Index对象以避免数据重复
- axis: int or str, optional
-
要定位的轴。可以是轴名称(‘index’, ‘columns’)或数字(0, 1)。
- copy bool, default True
-
即使传入的索引相同,也返回一个新对象。
- fill_value scalar, default np.NaN
-
用于缺失值的值。默认为 NaN,但可以是任何“兼容”的值。
- Returns
-
- DataFrame with changed index.
另请参阅
-
DataFrame.set_index
-
设置行标签。
-
DataFrame.reset_index
-
删除行标签或将它们移动到新列。
示例
DataFrame.reindex
支持两种调用格式-
(index=index_labels, columns=column_labels, ...)
-
(labels, axis={'index', 'columns'}, ...)
我们 强烈 建议使用关键字参数来明确您的意图。
创建一个包含一些虚构数据的DataFrame。
>>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] >>> df = ps.DataFrame({ ... 'http_status': [200, 200, 404, 404, 301], ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}, ... index=index, ... columns=['http_status', 'response_time']) >>> df http_status response_time Firefox 200 0.04 Chrome 200 0.02 Safari 404 0.07 IE10 404 0.08 Konqueror 301 1.00
创建一个新索引并重新索引数据框。默认情况下,在新索引中没有对应数据框记录的值会被分配为
NaN
。>>> new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', ... 'Chrome'] >>> df.reindex(new_index).sort_index() http_status response_time Chrome 200.0 0.02 Comodo Dragon NaN NaN IE10 404.0 0.08 Iceweasel NaN NaN Safari 404.0 0.07
我们可以通过传递一个值给关键字
fill_value
来填充缺失的值。>>> df.reindex(new_index, fill_value=0, copy=False).sort_index() http_status response_time Chrome 200 0.02 Comodo Dragon 0 0.00 IE10 404 0.08 Iceweasel 0 0.00 Safari 404 0.07
我们也可以重新索引列。
>>> df.reindex(columns=['http_status', 'user_agent']).sort_index() http_status user_agent Chrome 200 NaN Firefox 200 NaN IE10 404 NaN Konqueror 301 NaN Safari 404 NaN
或者我们可以使用“axis-style”关键字参数
>>> df.reindex(['http_status', 'user_agent'], axis="columns").sort_index() http_status user_agent Chrome 200 NaN Firefox 200 NaN IE10 404 NaN Konqueror 301 NaN Safari 404 NaN
为了进一步说明
reindex
中的填充功能,我们将创建一个具有单调递增索引的数据框(例如,一系列日期)。>>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') >>> df2 = ps.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, ... index=date_index) >>> df2.sort_index() prices 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
假设我们决定扩展数据框以覆盖更广泛的日期范围。
>>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D') >>> df2.reindex(date_index2).sort_index() prices 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