0

I am trying to figure out the names who only have specific column value and nothing else.

I have tried filtering the rows according to the column value but that isn't what I want, I want the names who only went to eat pizza.

I want names who only had pizza, so my code should return John only and not peter as john only had pizza

Click to view data frame

  • Possible duplicate of [extract column value based on another column pandas dataframe](https://stackoverflow.com/questions/36684013/extract-column-value-based-on-another-column-pandas-dataframe) – Mohit Motwani Jul 15 '19 at 06:08
  • Try: `df.loc[df['Restaurant'] == 'pizza', 'Name']` – Mohit Motwani Jul 15 '19 at 06:09
  • Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas) – M_S_N Jul 15 '19 at 06:11
  • @MohitMotwani: I don't think it a dup of the link you posted. He only wants `John`, yours will show all names having `Restaurant` of `pizza` – Andy L. Jul 15 '19 at 06:43

1 Answers1

1

Your description is not clear. At first, it looks like a simple .loc will be enough. However, after viewing your picture of sample data, I realized it is not that simple. To get what you want, you need to identify duplicated or non-duplicated names having one Restaurant value only, and pick it. To do this, you need to use nunique and check it eq(1), and assign it a mask m. Finally, using m with slicing to get your desire output:

Your sample data:

In [512]: df
Out[512]:
    Name    Restaurant
0   john  pizza
1  peter    kfc
2   john  pizza
3  peter  pizza
4  peter    kfc
5  peter  pizza
6   john  pizza

m = df.groupby('Name').Restaurant.transform('nunique').eq(1)
df[m]

Out[513]:
   Name    Res
0  john  pizza
2  john  pizza
6  john  pizza

If you want to show only one row, just chain additional .drop_duplicates

df[m].drop_duplicates()

Out[515]:
   Name    Restaurant
0  john  pizza
Andy L.
  • 24,909
  • 4
  • 17
  • 29