【问题标题】:Modify pandas series inplace, update reference to modified entries automatically就地修改熊猫系列,自动更新对修改条目的引用
【发布时间】:2019-12-16 13:16:30
【问题描述】:

我有一个熊猫系列,比如下面的my_series。我想创建对某些值的引用,以便在更新原始系列时更新引用。

>>> import pandas as pd
>>> my_series = pd.Series(dict(x=0, y=1, z=2))
>>> my_series
x    0
y    1
z    2
dtype: int64

>>> reference = my_series[['x', 'y']] # This doesn't work
>>> my_series.x = 10
>>> reference
x    0
y    1
dtype: int64

我想要的输出是

>>> reference
x    10
y    1
dtype: int64

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需使用 loc

    >>> my_series = pd.Series(dict(x=0, y=1, z=2))
    >>> reference = my_series.loc['x':'y']
    >>> my_series.x = 10
    >>> reference
    x    10
    y     1
    dtype: int64
    

    【讨论】:

    • 这样修改reference不会改变my_series对应的入口
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多