Getting Unique values from a column in Pandas dataframe

Getting Unique values from a column in Pandas dataframe

To get unique values from a column in a pandas DataFrame, you can use the unique() method.

Here's how you can do it:

  1. Import Necessary Library:

    First, make sure you've imported the pandas library:

    import pandas as pd 
  2. Sample DataFrame:

    Let's consider a sample DataFrame:

    data = { 'A': [1, 2, 3, 4, 5, 2, 4], 'B': ['a', 'b', 'c', 'a', 'b', 'b', 'd'] } df = pd.DataFrame(data) 
  3. Get Unique Values:

    To get unique values from column 'A':

    unique_A = df['A'].unique() print(unique_A) # Outputs: [1 2 3 4 5] 

    Similarly, for column 'B':

    unique_B = df['B'].unique() print(unique_B) # Outputs: ['a' 'b' 'c' 'd'] 

If you want the number of unique values, you can use the nunique() method:

count_unique_A = df['A'].nunique() print(count_unique_A) # Outputs: 5 

Additionally, if you want a Series of value counts, you can use the value_counts() method:

value_counts_A = df['A'].value_counts() print(value_counts_A) 

This will return the frequency of each unique value in the column.


More Tags

navbar geom-hline excel machine-code fuzzyjoin linearlayoutmanager rolling-computation android-contentresolver elasticsearch-plugin closures

More Programming Guides

Other Guides

More Programming Examples