pandas 用另一个系列的值覆盖(更新)一个熊猫系列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18992857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:11:26  来源:igfitidea点击:

Overwriting (updating) a pandas Series with values from another Series?

pythonpandas

提问by Dun Peal

I have two pandas Series: serand ovr.

我有两个Pandas系列:serovr

sercontains objects, and ovris a sparse Seriesof objects and None's. serand ovrshare the same index, and I'd like to overwrite every value of serwith its corresponding value of ovr, unless that corresponding value is None.

ser包含对象,并且ovr是稀疏Series的对象 和Noneserovr共享相同的索引,我想ser用其对应的 值覆盖 的每个值ovr,除非对应的值是None

What's an efficient way to accomplish that?

实现这一目标的有效方法是什么?

回答by Andy Hayden

I recommend using NaN for missing data rather than None(Note: this technique also works with None).

我建议对缺失数据使用 NaN 而不是 None(注意:此技术也适用于 None)。

In [1]: s1 = pd.Series([1, np.nan, 3, 4, 5, np.nan])

In [2]: s2 = pd.Series([7, 2, 3, np.nan, np.nan])

First see that s2 values which are not NaN (or None), these are those which you want to update s1 with:

首先看到不是 NaN(或无)的 s2 值,这些是您想要更新 s1 的值:

In [3]: s2[s2.notnull()]
Out[3]:
0    7
1    2
2    3
dtype: float64

And then you can update the values of s1 with these:

然后你可以用这些更新 s1 的值:

In [4]: s1.update(s2[s2.notnull()])

In [5]: s1
Out[5]:
0     7
1     2
2     3
3     4
4     5
5   NaN
dtype: float64