Can someone please help me with my current error or suggest another way of doing this ? Thanks a lot in advance
I have bellow data frame given bellow :-
JavaScript
x
7
1
GroupName Id Type1 Type2 Type 3
2
ABC 1 100 0 0
3
2 0 -100 0
4
3 0 100 100
5
DEF 4 100 0 0
6
5 0 100 0
7
I want to filter the data frame such that it returns me all the rows and the GroupName where one or more of the columns (Type1 /Type2/Type3) has +ve and a -ve value .
OUTPUT in the above df it will return be only
JavaScript
1
5
1
GroupName Id Type1 Type2 Type 3
2
ABC 1 100 0 0
3
2 0 **-100** 0
4
3 0 100 **100**
5
I tried
JavaScript
1
2
1
df[df.gt(0).any(axis=1) & df.lt(0).any(axis=1)]
2
getting error
JavaScript
1
3
1
if level_codes[key] == -1:
2
IndexError: index 0 is out of bounds for axis 0 with size 0
3
I created this df by using a pivot table
JavaScript
1
3
1
df= old_df.pivot_table(index=["GroupName","Id"], columns="Type", values="Value",
2
aggfunc=np.sum)
3
Advertisement
Answer
IIUC:
JavaScript
1
15
15
1
import numpy as np
2
import pandas as pd
3
4
def posandneg(d):
5
return np.in1d([1, -1], np.sign(d)).all()
6
7
df.groupby(level=0).filter(posandneg)
8
9
Type1 Type2 Type 3
10
GroupName Id
11
ABC 1 100 0 0
12
2 0 -100 0
13
3 0 100 100
14
•
15