Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I select one of each category with a Pandas DataFrame in Python?

I have a dataframe that looks like this:

author|string
abc|hi
abc|yo
def|whats
ghi|up
ghi|dog

how can I select only one row per author? I’m at a loss.
I want to do something like this:

df.loc[unique authors].sample(n=1000)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and get something like this:

author|string
abc|hi
def|whats
ghi|up

I was thinking of converting the author column to categories, but I don’t know where to go from there.

I could just do something like this but it seems stupid.

author_list = df['author'].unique().tolist()
indexes = []
for author in author_list:
  indexes.append(df.loc[df['author'] == author].iloc[0].index)
df.iloc[indexes].sample(n=1000)

>Solution :

You can do

out = df.drop_duplicates('author')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading