1

I have an carid and I would like to see all buyers who had something to do with this carid. So I would like to have all buyers who have bought carid 3. How do I do that?

import pandas as pd
d = {'Buyerid': [1,1,2,2,3,3,3,4,5,5,5],
     'Carid': [1,2,3,4,4,1,2,4,1,3,5]}

df = pd.DataFrame(data=d)
print(df)

    Buyerid  Carid
0         1      1
1         1      2
2         2      3
3         2      4
4         3      4
5         3      1
6         3      2
7         4      4
8         5      1
9         5      3
10        5      5

# What I want

    Buyerid  Carid
2         2      3
3         2      4
8         5      1
9         5      3
10        5      5

I have already tested this df = df.loc[df['Carid']==3,'Buyerid'], but this only gives me the line with CardID 3 but not the complete buyer. How to select rows from a DataFrame based on column values

I looked at that, but I only get this here

   Buyerid  Carid
2         2      3
9         5      3
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
Ella
  • 361
  • 3
  • 9
  • Is `carid` the `itemid`? – Dani Mesejo Nov 29 '20 at 14:18
  • Yes you're right. thanks! – Ella Nov 29 '20 at 14:19
  • Welcome to SO. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask] and the other links found on that page. Invest some time with the Pandas user guide practicing the examples. https://pandas.pydata.org/docs/user_guide/index.html, [https://pandas.pydata.org/docs/user_guide/10min.html#boolean-indexing](https://pandas.pydata.org/docs/user_guide/10min.html#boolean-indexing) – wwii Nov 29 '20 at 14:24
  • @wwii I'm not sure to what extent that is a good duplicate – Dani Mesejo Nov 29 '20 at 14:24
  • @wwii Well, I've already tried something, but I always only get one line and not the entire buyer .... – Ella Nov 29 '20 at 14:25
  • @DaniMesejo you are right..this is not dupe..reopening. – Shubham Sharma Nov 29 '20 at 14:26

2 Answers2

1

Do the following:

import pandas as pd

d = {'Buyerid': [1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5],
     'Carid': [1, 2, 3, 4, 4, 1, 2, 4, 1, 3, 5]}

df = pd.DataFrame(data=d)

# get all buyers
buyers = set(df.loc[df['Carid'] == 3, 'Buyerid'])

# boolean mask for filtering
mask = df['Buyerid'].isin(buyers)

print(df[mask])

Output

    Buyerid  Carid
2         2      3
3         2      4
8         5      1
9         5      3
10        5      5
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • Yes, only I was only able to vote in 3 minutes, that's why I couldn't accept it directly – Ella Nov 29 '20 at 14:31
0

You can use df.loc:

df.loc[df['Carid']==3,'Buyerid']
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • Thank you, but that only gives me the one line with the carid I would like to have the complete buyer with it – Ella Nov 29 '20 at 14:26