In Python Pandas, a logical operation

I perform a boolean operation on two Series. I was expecting the boolean operation to automatically perform the operation corresponding to the same index. But instead, he simply does so by order. Is this expected behavior, or is there some other way to do this? Thanks

b Out[47]: AEIS False AAPL True ACFN False Name: OldPosition, dtype: bool a Out[48]: AAPL True ACFN False AEIS True dtype: bool a&b Out[50]: AAPL False ACFN False AEIS False dtype: bool 
+6
source share
2 answers

The error seems to me:

 In [1]: a = pd.Series([True, False, True], list('bca')) In [2]: b = pd.Series([False, True, False], list('abc')) In [3]: a & b Out[3]: b False c False a False dtype: bool 

One workaround is to reindex using the same index:

 In [4]: index = a.index | b.index In [5]: a.reindex(index) & b.reindex(index) Out[5]: a False b True c False dtype: bool 
+6
source

If you have the same series of lengths, you should be able to use the index of one series to order another series to suit your needs.

 In [15]: a[b.index] Out[15]: a True b True c False dtype: bool In [16]: b Out[16]: a False b True c False dtype: bool In [17]: a[b.index] & b Out[17]: a False b True c False dtype: bool 

I can confirm that with pandas 0.17.1 the desired functionality is in place.

 In [1]: import pandas as pd In [2]: a = pd.Series([True, False, True], list('bca')) In [3]: b = pd.Series([False, True, False], list('abc')) In [4]: b & a Out[4]: a False b True c False 
+2
source

Source: https://habr.com/ru/post/954381/


All Articles