【问题标题】:Replace values of a pandas Series from a list从列表中替换熊猫系列的值
【发布时间】:2016-05-28 19:20:58
【问题描述】:

假设我有一个系列profile,其中包含:

settings-win.data.microsoft.com    1
www.facebook.com                   0.4
clients4.google.com                1
plus.google.com                    0.86

还有一个列表new_val,其中包含:

[0.8408964152537145, 0, 1.5, 0]

如何将profile 系列中的所有值替换为列表?应该是:

settings-win.data.microsoft.com    0.8408964152537145
www.facebook.com                   0
clients4.google.com                1.5
plus.google.com                    0

我尝试了Series.replace(),但它似乎不起作用。

附言。我也对如何以及何时使用 .replace() 感到困惑,所以如果您能进一步解释,将不胜感激。

【问题讨论】:

  • profile.values = new_val

标签: python list pandas series


【解决方案1】:

我认为您可以使用旧indexSeries s 和列表li 的值创建新的Series

print s
settings-win.data.microsoft.com    1.00
www.facebook.com                   0.40
clients4.google.com                1.00
plus.google.com                    0.86
Name: profile, dtype: float64

new_val = [0.8408964152537145, 0, 1.5, 0]
s1 = pd.Series(new_val, index=s.index, name='profile')

print s1
settings-win.data.microsoft.com    0.840896
www.facebook.com                   0.000000
clients4.google.com                1.500000
plus.google.com                    0.000000
Name: profile, dtype: float64

但也许更好的是replacemap by dictionary,但结果不同,因为第一个和第三个值相同 - doc

d = {1: 0.8408964152537145, 0.4: 0, 0.86: 0}
print d
{1: 0.8408964152537145, 0.4: 0, 0.86: 0}

print s.replace(d)
settings-win.data.microsoft.com    0.840896
www.facebook.com                   0.000000
clients4.google.com                0.840896
plus.google.com                    0.000000
Name: profile, dtype: float64

print s.map(d)
settings-win.data.microsoft.com    0.840896
www.facebook.com                   0.000000
clients4.google.com                0.840896
plus.google.com                    0.000000
Name: profile, dtype: float64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2022-06-24
    • 2019-02-05
    • 2017-02-25
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多