【Pandas】pandas Series update
Pandas2.2 Series
Computations descriptive stats
| 方法 | 描述 |
|---|---|
| Series.compare(other[, align_axis, …]) | 用于比较两个 Series |
| Series.update(other) | 用于用另一个序列(Series)中的值更新当前序列 |
pandas.Series.update
pandas.Series.update(other) 方法用于用另一个序列(Series)中的值更新当前序列。它会根据索引对齐来更新当前序列中与 other 序列有相同索引的元素。
详细描述
- 参数:
other: 另一个Series对象,其值将用于更新当前Series。
- 行为:
- 如果
other中的索引在当前Series中存在,则对应的值会被更新。 - 如果
other中的索引在当前Series中不存在,则不会添加到当前Series中。 - 该方法是原地操作,即直接修改当前
Series而不返回新对象。
- 如果
示例代码及结果
import pandas as pd
# 创建两个 Series
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5], index=['b', 'd'])
print("原始 s1:")
print(s1)
# 使用 update 方法
s1.update(s2)
print("\n更新后的 s1:")
print(s1)
输出结果
原始 s1:
a 1
b 2
c 3
dtype: int64
更新后的 s1:
a 1
b 4
c 3
dtype: int64
结果解释
- 在示例中,
s1的索引为['a', 'b', 'c'],而s2的索引为['b', 'd']。 s2中的索引'b'存在于s1中,因此s1中索引'b'的值从2更新为4。s2中的索引'd'不在s1中,因此不会影响s1。
