pandas replacen内部使用函数
时间: 2023-12-03 09:45:24 浏览: 87
在 Pandas 中,`replace()` 方法内部使用了 `_get_mapper()` 函数来获取一个字典映射,将要替换的值映射为新的值。`_get_mapper()` 函数的源代码如下:
```python
def _get_mapper(self, mapper=None):
if callable(mapper):
mapper = mapper(self)
if isinstance(mapper, (dict, Series)):
if isinstance(mapper, dict):
keys = list(mapper.keys())
if any(k is None or com.is_datetime64tz(k) for k in keys):
keys = [com.pandas_ify(k) for k in keys]
values = [mapper[k] for k in keys]
else:
keys = mapper.index
values = mapper.values
return dict(zip(keys, values))
# if a list of tuples, convert to dict
elif isinstance(mapper, (list, tuple)):
if not all(isinstance(x, (tuple, list)) and len(x) == 2 for x in mapper):
raise ValueError("If 'mapper' is a list or tuple, it should be a list/tuple of tuples")
return dict((k, v) for k, v in mapper)
elif mapper is None:
return {}
else:
raise TypeError("If 'mapper' is None, it is expected to be a dict, list or tuple, not {0}".format(type(mapper)))
```
该函数的作用是将传入的 `mapper` 对象(可以是字典、Series、列表或元组)转换为一个字典映射,如果 `mapper` 是一个可调用对象,则调用该对象并传入当前 DataFrame/Series 对象作为参数。
`replace()` 方法将传入的 `to_replace` 参数和 `value` 参数都作为 `mapper` 参数传入 `_get_mapper()` 函数,然后将返回的字典映射应用到 DataFrame/Series 中,实现值的替换。
阅读全文