从列表中替换 pandas 系列的值
Replace values of a pandas Series from a list
假设我有一个系列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()
,但它似乎不起作用。
PS。我也对如何以及何时使用 .replace()
感到困惑,所以如果您能进一步解释它,我们将不胜感激。
我认为您可以使用旧 Series
s
的 index
和列表 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
但也许更好的是 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
假设我有一个系列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()
,但它似乎不起作用。
PS。我也对如何以及何时使用 .replace()
感到困惑,所以如果您能进一步解释它,我们将不胜感激。
我认为您可以使用旧 Series
s
的 index
和列表 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
但也许更好的是 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