cjavapy编程之程

Python pandas.DataFrame.reindex函数方法的使用

pandas.DataFrame.reindex() 函数用于按指定的行索引或列标签对 DataFrame 进行重新排列、对齐或扩展。它可以用来更改索引顺序、添加缺失标签(会填充 NaN)或删除不存在于目标索引中的行/列。常用于数据对齐、缺失值插入和统一多个数据集的结构。支持设置填充值(fill_value)和填充方法(如 method='ffill')来处理新增索引带来的缺失值。本文主要介绍一下Pandas中pandas.DataFrame.reindex方法的使用。

DataFrame.reindex(self, labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None) [source]

使用可选的填充逻辑(如 methodfill_value)将 DataFrame 对齐到新的索引。

对于在新索引中但不在原索引中的位置,将填充为 NA/NaN
如果新索引与原索引不完全相同,且未显式设置 copy=False,则返回一个新的 DataFrame 对象。

参数 :

labels : 类数组,可选

新labels/index "axis"指定的轴与之一致。

index, columns : 类似数组,可选

要使用的新labels/index 引要符合。

最好是一个Index对象,以避免重复数据。

method : {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}

默认 None

用于在重新索引的DataFrame中填充孔的方法。

请注意:这仅适用于具有

单调递增/递减索引的DataFrames/Series。

1) None (default): 不填补空白

2) pad/ffill

将上一个有效观察值向前传播到下一个有效值。

3) backfill/bfill

使用下一个有效观察值填充空白。

4) nearest

使用最近的有效观测值来填补空白。

copy : boolean, 默认 True

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

level : intname

在一个级别上广播,

在传递的MultiIndex级别上匹配索引值。

fill_value : scalar, 默认为 np.NaN

用于缺失值的值。默认为NaN

但可以是任何“compatible”值。

limit : int, 默认 None

向前或向后填充的连续元素的最大数量。

tolerance: 可选

不精确匹配的原始标签和新标签之间的最大距离。

在匹配位置的索引值最符合公式

abs(index[indexer] - target) <= tolerance

公差可以是一个标量值,

它对所有值应用相同的tolerance;

也可以是类似列表的值,

它对每个元素应用可变的tolerance

list-like包括list、tuple、array、Series

并且必须与索引相同大小,

其dtype必须与索引的类型完全匹配。

新版本0.21.0:(列表式tolerance)

返回值 :

更改索引的DataFrame。

例子

DataFrame.reindex 支持两种调用约定

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

1)基本行重排(默认填充 NaN

import pandas as pd

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)

new_index = ['Safari', 'Iceweasel', 
'Comodo Dragon', 'IE10', 'Chrome']
reindexed_df = df.reindex(new_index)

print(reindexed_df)

2)使用 fill_value 填充缺失数据

import pandas as pd

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)

new_index = ['Safari', 'Iceweasel', 
'Comodo Dragon', 'IE10', 'Chrome']

# 填充缺失数据为 0
filled_df = df.reindex(new_index, fill_value=0)
print(filled_df)

# 填充为字符串 'missing'
filled_str_df = df.reindex(new_index,
fill_value='missing')
print(filled_str_df)

3)重新排列列

import pandas as pd

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)

new_index = ['Safari', 'Iceweasel', 
'Comodo Dragon', 'IE10', 'Chrome']

# 添加一个不存在的新列 'user_agent'
df_col_reindexed = df.reindex(columns=['http_status', 'user_agent'])
print(df_col_reindexed)

# 或者使用 axis='columns' 参数
df_col_axis = df.reindex(['http_status', 'user_agent'], axis='columns')
print(df_col_axis)

4)日期索引扩展并填充(时间序列处理)

import pandas as pd
import numpy as np

date_index = pd.date_range('2010-01-01', periods=6, freq='D')
df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, index=date_index)

# 扩展索引范围
date_index2 = pd.date_range('2009-12-29', periods=10, freq='D')
df2_expanded = df2.reindex(date_index2)

print(df2_expanded)

5)使用 method='bfill' 进行后向填充

import pandas as pd
import numpy as np

date_index = pd.date_range('2010-01-01',
periods=6, freq='D')
df2 = pd.DataFrame({"prices": [100, 101, 
np.nan, 100, 89, 88]}, index=date_index)

# 扩展索引范围
date_index2 = pd.date_range('2009-12-29', 
periods=10, freq='D')
df2_expanded = df2.reindex(date_index2)

df2_bfill = df2.reindex(date_index2, 
method='bfill')
print(df2_bfill)

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

推荐阅读
cjavapy编程之路首页