Skip to main content
 首页 » 编程设计

python之返回更新系列的 pandas.Series 方法

2024年12月31日7kuangbin

是否有一种 Series 方法的作用类似于更新但返回更新后的系列而不是就地更新?

换句话说,有没有更好的方法来做到这一点:

# Original series 
ser1 = Series([10, 9, 8, 7], index=[1,2,3,4]) 
 
# I want to change ser1 to be [10, 1, 2, 7] 
adj_ser = Series([1, 2], index=[2,3]) 
 
adjusted = my_method(ser1, adj_ser) 
 
# Is there a builtin that does this already? 
def my_method(current_series, adjustments): 
    x = current_series.copy() 
    x.update(adjustments) 
    return(x) 

请您参考如下方法:

一个可能的解决方案应该是 combine_first ,但它通过 ser1 更新 adj_ser,还将整数转换为 float:

adjusted = adj_ser.combine_first(ser1) 
print (adjusted) 
1    10.0 
2     1.0 
3     2.0 
4     7.0 
dtype: float64