pandas.Series.reindex#

Series.reindex(index=None, *, axis=None, method=None, copy=None, level=None, fill_value=None, limit=None, tolerance=None)[源代码]#

使用可选的填充逻辑使Series符合新索引。

在没有先前索引值的位置插入 NA/NaN。除非新索引与当前索引等效且 copy=False,否则会生成一个新对象。

Parameters:
indexarray-like, optional

索引的新标签。最好是 Index 对象,以避免重复数据。

axisint 或 str,可选

未使用。

<strong>method</strong>{None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}

用于填充重索引 DataFrame 中缺失值的方法。请注意:这仅适用于索引单调递增/递减的 DataFrame/Series。

  • None(默认):不填充间隙

  • pad / ffill:将最后一个有效观测值向前传播到下一个有效值。

  • backfill / bfill:使用下一个有效观测值填充间隙。

  • nearest:使用最近的有效观测值填充间隙。

copybool, default True

返回一个新对象,即使传入的索引相同。

备注

copy 关键字在 pandas 3.0 中将更改行为。Copy-on-Write 将默认启用,这意味着所有带有 copy 关键字的方法都将使用惰性复制机制来延迟复制并忽略 copy 关键字。copy 关键字将在 pandas 的未来版本中移除。

通过启用 copy on write pd.options.mode.copy_on_write = True,您可以获得未来的行为和改进。

levelint 或 str

跨级别广播,匹配 MultiIndex 级别上的索引值。

fill_value标量,默认 np.nan

用于缺失值的数值。默认为 NaN,但可以是任何“兼容”值。

<strong>limit</strong>int,默认 None

向前或向后填充的连续元素的连续数量的上限。

toleranceoptional

对于非精确匹配,原始标签和新标签之间的最大距离。索引在匹配位置的值必须满足方程 abs(index[indexer] - target) <= tolerance

tolerance 可以是标量值,它将相同的容差应用于所有值,也可以是类列表的值,它将可变容差应用于每个元素。类列表包括 list、tuple、array、Series,并且必须与索引大小相同,其 dtype 必须与索引的确切类型匹配。

Returns:
已更改索引的 Series。

参见

DataFrame.set_index

设置行标签。

DataFrame.reset_index

移除行标签或将它们移动到新列。

DataFrame.reindex_like

将此对象更改为与另一个 DataFrame 具有相同的索引。

Examples

DataFrame.reindex 支持两种调用约定

  • (index=index_labels, columns=column_labels, ...)

  • (labels, axis={'index', 'columns'}, ...)

我们*强烈*建议使用关键字参数来明确您的意图。

创建一个带有虚假数据的 DataFrame。

>>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
>>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301],
...                   'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},
...                   index=index)
>>> 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

创建一个新的索引并重新索引 DataFrame。默认情况下,新索引中没有对应 DataFrame 记录的值将被分配 NaN

>>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',
...              'Chrome']
>>> df.reindex(new_index)
               http_status  response_time
Safari               404.0           0.07
Iceweasel              NaN            NaN
Comodo Dragon          NaN            NaN
IE10                 404.0           0.08
Chrome               200.0           0.02

我们可以通过将值传递给关键字 fill_value 来填充缺失值。由于索引不是单调递增或递减的,我们无法使用关键字 method 的参数来填充 NaN 值。

>>> df.reindex(new_index, fill_value=0)
               http_status  response_time
Safari                 404           0.07
Iceweasel                0           0.00
Comodo Dragon            0           0.00
IE10                   404           0.08
Chrome                 200           0.02
>>> df.reindex(new_index, fill_value='missing')
              http_status response_time
Safari                404          0.07
Iceweasel         missing       missing
Comodo Dragon     missing       missing
IE10                  404          0.08
Chrome                200          0.02

我们也可以重新索引列。

>>> df.reindex(columns=['http_status', 'user_agent'])
           http_status  user_agent
Firefox            200         NaN
Chrome             200         NaN
Safari             404         NaN
IE10               404         NaN
Konqueror          301         NaN

或者我们可以使用“axis-style”关键字参数

>>> df.reindex(['http_status', 'user_agent'], axis="columns")
           http_status  user_agent
Firefox            200         NaN
Chrome             200         NaN
Safari             404         NaN
IE10               404         NaN
Konqueror          301         NaN

为了进一步说明 reindex 中的填充功能,我们将创建一个索引单调递增的 DataFrame(例如,一系列日期)。

>>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')
>>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]},
...                    index=date_index)
>>> df2
            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

假设我们决定扩展 DataFrame 以覆盖更长的时间范围。

>>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')
>>> df2.reindex(date_index2)
            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

在原始 DataFrame 中没有值的索引条目(例如,’2009-12-29’)默认用 NaN 填充。如果需要,我们可以使用几种选项之一来填充缺失值。

例如,要将最后一个有效值向后传播以填充 NaN 值,请将 bfill 作为参数传递给 method 关键字。

>>> df2.reindex(date_index2, method='bfill')
            prices
2009-12-29   100.0
2009-12-30   100.0
2009-12-31   100.0
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

请注意,原始 DataFrame 中存在的 NaN 值(在索引值为 2010-01-03 时)不会被任何值传播方案填充。这是因为在重新索引时进行填充不会查看 DataFrame 的值,而只会比较原始索引和目标索引。如果您确实想填充原始 DataFrame 中存在的 NaN 值,请使用 fillna() 方法。

有关更多信息,请参阅 user guide