anobilisgorse
anobilisgorse

Reputation: 906

Replace values of a pandas Series from a list

Suppose I have a series profile that contains:

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

And a list new_val that contains:

[0.8408964152537145, 0, 1.5, 0]

How do I replace all the values in my profile series with the list? It should be:

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

I tried the .replace() of Series but it doesn't seem to work.

PS. I'm also confused on how and when to use .replace() so if you could explain it further, it will be very appreciated.

Upvotes: 3

Views: 2299

Answers (1)

jezrael
jezrael

Reputation: 863751

I think you can create new Series with index of old Series s and values of list li:

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

But maybe better is replace or map by dictionary, but result is different, because first and third value is same - 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

Upvotes: 3

Related Questions