Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - Get names based on another column in pandas dataframe

I need to get the first and last names of people who work in HR department.


    FirstName   LastName        Year    Department
83  Joe         Faulk           2       Austin Public Library
84  Bryce       Benton          5       HR
85  Sarah       Cronin          7       Austin Public Library
86  Gabriel     Montgomery      2       Austin Resource Recovery
87  Patricia    Genty-Andrade   3       HR

This is my code it shows me error AttributeError: 'DataFrame' object has no attribute 'unique'


names = df.iloc[:, 0:4][df['Department'] == 'HR'].unique()

I need the output to be like this

   FirstName   LastName        Department
0  Joe         Faulk           HR
1  Bryce       Benton          HR
2  Sarah       Cronin          HR
3  Gabriel     Montgomery      HR
4  Patricia    Genty-Andrade   HR

question from:https://stackoverflow.com/questions/66056422/get-names-based-on-another-column-in-pandas-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use drop_duplicates instead of unique, as unique is for Series.

df.loc[df['Department'] == 'HR',
       ['FirstName', 'LastName', 'Department']].drop_duplicates()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...