Reputation: 436
I have a series. I would like to extract some elements from that series using a mask and put them back to same or different locations in the same series using a different mask. Something like this:
s = pd.Series(randn(5))
s
0 0.466829
1 -1.821200
2 0.025857
3 0.238267
4 2.192390
dtype: float64
s[pd.Series([False,True,False,True,False])] = s[pd.Series([True,False,True,False,False])]
s
0 0.466829
1 NaN
2 0.025857
3 NaN
4 2.192390
dtype: float64
As you can see that example doesn't work. Note that in my use case, both masks are guaranteed to have the same number of True
and False
elements.
Upvotes: 3
Views: 2771
Reputation: 36545
When setting values on a Pandas series, the index is used to align values. So for you example, even though the number of values is the same, the indexes are different, hence the null values. If you want to override this behavior, you can use values
to access the underlying array of the Series (ignoring the index). Also you don't need to cast your indexers explicitly with pd.Series
, this will happen implicitly if you past a list:
s[[False,True,False,True,False]] = s[[True,False,True,False,False]].values
s
Out[300]:
0 0.013654
1 0.013654
2 0.691198
3 0.691198
4 0.344096
dtype: float64
Upvotes: 2