3

I have a large dataframe df1 that looks like this:

DeviceID     Location
1            Internal
1            External   
2            Internal   
2            Internal   
3            Internal   
3            External   
3            Internal
4            Internal   
4            Internal
5            External   
5            Internal   

I'm trying to find and select the rows where a single DeviceID is recorded with both "Internal" AND "External" values in the Location column.

The next step would be to drop these rows from the dataframe. The final dataframe df2 would look like so:

DeviceID     Location
2            Internal   
2            Internal   
4            Internal   
4            Internal   

What I've attempted so far is: indexDI = df[(df['Location'] == 'Internal') & df['Location'] == 'External') ].index df.drop(indexDI, inplace = True)

but this seems to have to dropped all the rows with "Internal".

Any help would be appreciated :)

0

3 Answers 3

1

You can groupby, transform with the nunique to see which gorups contain two different values and use the result to perform boolean indexing on the dataframe:

df[df.groupby('DeviceID').Location.transform('nunique').eq(1)]

     DeviceID  Location
2         2  Internal
3         2  Internal
7         4  Internal
8         4  Internal

Simple add reset_index(drop=True) for a panda's RangeIndex

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need .loc. reset_index is not really needed either.
Yup, though a RangeIndex will presumably be what op wants. But yeah I guess iI'll just add a note @QuangHoang
0

One solution would be to loop through the entire df and drop the rows if both conditions are met. Right now your solution checks the same row which can't have both criteria at once.

1 Comment

It would be appreciable if you show running example.
0

one more solution without .loc,

df[(df.groupby('DeviceID').transform('nunique')!=2).values]

O/P:

   DeviceID  Location
2         2  Internal
3         2  Internal
7         4  Internal
8         4  Internal

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.