【Pandas】pandas Series rename
Pandas2.2 Series
Computations descriptive stats
方法 | 描述 |
---|---|
Series.align(other[, join, axis, level, …]) | 用于将两个 Series 对齐,使其具有相同的索引 |
Series.case_when(caselist) | 用于根据条件列表对 Series 中的元素进行条件判断并返回相应的值 |
Series.drop([labels, axis, index, columns, …]) | 用于从 Series 中删除指定的行或列(对于 Series 来说,通常是删除行) |
Series.droplevel(level[, axis]) | 用于从多层索引(MultiIndex)的 Series 中删除指定的索引层级 |
Series.drop_duplicates(*[, keep, inplace, …]) | 用于从 Series 中删除重复的值 |
Series.duplicated([keep] ) | 用于检测 Series 中的重复值 |
Series.equals(other) | 用于比较两个 Series 对象是否完全相等的方法 |
Series.first(offset) | 用于根据日期偏移量(offset )选择 Series 中时间序列数据的初始部分 |
Series.head([n] ) | 用于返回 Series 的前 n 个元素 |
Series.idxmax([axis, skipna]) | 用于返回 Series 中最大值的索引 |
Series.idxmin([axis, skipna]) | 用于返回 Series 中最小值的索引 |
Series.isin(values) | 用于检查 Series 中的每个元素是否存在于给定的值集合 values 中 |
Series.last(offset) | 用于根据日期偏移量(offset )选择 Series 中时间序列数据的末尾部分 |
Series.reindex([index, axis, method, copy, …]) | 用于重新索引 Series 对象的方法 |
Series.reindex_like(other[, method, copy, …]) | 用于将 Series 对象重新索引以匹配另一个 Series 或 DataFrame 的索引的方法 |
Series.rename([index, axis, copy, inplace, …]) | 用于重命名 Series 对象的索引或轴标签的方法 |
pandas.Series.rename
pandas.Series.rename
是一个用于重命名 Series
对象的索引或轴标签的方法。它允许用户根据指定的映射或函数对索引进行重命名。以下是该方法的参数说明:
- index: 用于重命名索引的映射(字典、函数等)。
- axis: 指定要重命名的轴,对于
Series
可以忽略,默认为 0(行)。 - copy: 如果为 True,则返回一个新的副本;如果为 False,则返回视图,默认为 True。
- inplace: 如果为 True,则就地修改数据;如果为 False,则返回新的对象,默认为 False。
- level: 如果索引是 MultiIndex,则指定使用哪一级别进行重命名。
- errors: 控制错误处理方式,‘ignore’ 表示忽略错误,‘raise’ 表示抛出异常。
示例及结果
示例 1:使用字典重命名索引
import pandas as pd
# 创建一个简单的 Series
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
# 使用字典重命名索引
s_renamed = s.rename(index={'a': 'A', 'b': 'B'})
print("原始 Series:")
print(s)
print("\n重命名后的 Series:")
print(s_renamed)
输出结果
原始 Series:
a 1
b 2
c 3
dtype: int64
重命名后的 Series:
A 1
B 2
c 3
dtype: int64
在这个例子中,我们使用字典将索引 'a'
和 'b'
分别重命名为 'A'
和 'B'
,而 'c'
保持不变。
示例 2:使用函数重命名索引
# 使用函数重命名索引
s_renamed_func = s.rename(index=str.upper)
print("\n使用函数重命名后的 Series:")
print(s_renamed_func)
输出结果
使用函数重命名后的 Series:
A 1
B 2
C 3
dtype: int64
在这个例子中,我们使用 str.upper
函数将所有索引转换为大写。
示例 3:就地修改
# 就地修改 Series 的索引
s.rename(index=str.upper, inplace=True)
print("\n就地修改后的 Series:")
print(s)
输出结果
就地修改后的 Series:
A 1
B 2
C 3
dtype: int64
在这个例子中,我们通过设置 inplace=True
来就地修改 Series
的索引,而不是创建新的对象。
示例 4:处理 MultiIndex
# 创建一个带有 MultiIndex 的 Series
multi_index = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')], names=['first', 'second'])
s_multi = pd.Series([1, 2, 3], index=multi_index)
# 重命名 MultiIndex 的第一级
s_multi_renamed = s_multi.rename(index={'a': 'A', 'b': 'B'}, level='first')
print("\n原始 MultiIndex Series:")
print(s_multi)
print("\n重命名后的 MultiIndex Series:")
print(s_multi_renamed)
输出结果
原始 MultiIndex Series:
first second
a x 1
b y 2
c z 3
dtype: int64
重命名后的 MultiIndex Series:
first second
A x 1
B y 2
c z 3
dtype: int64
在这个例子中,我们仅重命名了 MultiIndex
的第一级(first
),而第二级(second
)保持不变。