1

im new to python and trying to work with dataframes manipulation:

I have a df with unique categories: I am unable to paste the dataframe because I use Spyder IDE and it is not interactive does not display all fields.

My input to get all these unique categories within a dataframe:

uc =[]
for i in df['Category']:
    if i[0] not in df['Category']:
        uc.append(i[0])
print(uc)

But when I use this script, I only receive the first letters of these categories:

Output:

['F', 'P', 'N', 'F', 'L', 'T', 'W', 'S', 'W', 'B', 'S', 'F', 'T', 'T', 'B', 'T', 'B', 'L', 'S', 'F', 'F', 'F', 'N', 'P', 'H', 'T', 'L', 'T', 'S', 'E', 'P', 'N', 'T', 'L', 'P', 'L', 'W', 'F', 'N', 'L', 'N', 'L', 'F', 'F', 'N', 'T', 'P', 'L', 'B', 'W', 'L', 'W', 'F', 'F', 'H', 'T', 'F', 'T', 'T', 'N', 'G', 'L', 'M', 'N', 'F', 'N', 'F', 'L', 'N', 'P', 'F', 'B', 'B', 'S', 'F', 'P', 'F', 'P', 'P', 'P', 'B', 'P', 'B', 'B', 'L', 'B', 'F', 'P', 'P', 'B', 'B', 'C', 'G', 'C', 'G', 'B', 'P', 'T', 'P', 'P', 'N', 'G', 'S', 'G', 'F', 'G', 'F', 'T', 'S', 'P', 'F', 'C', 'C', 'C', 'C', 'C', 'G', 'C', 'F', 'C', 'F', 'B', 'G', 'C', 'B', 'B', 'B', 'C', 'P', 'G', 'S', 'D', 'P', 'G', 'F', 'L', 'C', 'G', 'P', 'S', 'B', 'P', 'T', 'T', 'L', 'M', 'F', 'T', 'P', 'C', 'F', 'B', 'M', 'G', 'C', 'P', 'T', 'L', 'F', 'F', 'F', 'T', 'P', 'C', 'G', 'T', 'F', 'F', 'S', 'B', 'M', 'T', 'T', 'T', 'T', 'H', 'B', 'N', 'F', 'A', 'T', 'E', 'M', 'L', 'G', 'P', 'B', 'L', 'N', 'S', 'G', 'G', 'F', 'F', 'F', 'G', 'G', 'G', 'G', 'F', 'T', 'G', 'P', 'G', 'C', 'G', 'G', 'G', 'F', 'T', 'T', 'L', 'F', 'S', 'T', 'F', 'F', 'G', 'G', 'L', 'M', 'T', 'L', 'F', 'B', 'A', 'F', 'B', 'F', 'B', 'B', 'T', 'F', 'B', 'F', 'F', 'P', 'V', 'M', 'S', 'F', 'C', 'B', 'N', 'M', 'W', 'B', 'F', 'B', 'F', 'F', 'M', 'L']

How do I change my script to reveive unique categories within a dataframe?

3 Answers3

5

Try with

 df['Category'].unique()
4

print(df['Category'].unique()) see what you get.

Also, i[0] is retrieving the first char of a string value in the df['Category'].

also, if you are new to pandas, you MUST abandon the old habit of for loop. And always type() your result to obtain better understanding.

eliu
  • 2,390
  • 1
  • 17
  • 29
2

Do you want this?

uc = set(df['Category'])

This will create a set containing the unique values of 'Category'

LocoGris
  • 4,432
  • 3
  • 15
  • 30