Search code examples
pandasseabornpandas-groupbypandas-datareader

how to create new data frame from the output of value_counts()


i have a dataframe name 'df' and i run below code...

df['Station'].value_counts()

my Output will be:

Station 308A   -   3955

Station 329   -    3905

Station 313   -    2963

.....................

Station 381   -    2383

Name: Station, dtype: int64

Now i want to plot this in countplot:

sns.countplot(x= "Station", data=df['Station'].value_counts().head(30), palette="bright")

gives me error!!!

because i can only pass dataframe in Data ex: data=df

So my question i want output of this line df['Station'].value_counts() as a new data frame

so that i can directly pass it as sns(data=new_df)


Solution

  • You can filter top values by parameter order with value_counts and index:

    np.random.seed(34345)
    
    df = pd.DataFrame({'Station':np.random.randint(100, size=1000)}).astype(str).radd('station')
    print (df.head())
         Station
    0  station28
    1  station48
    2  station48
    3  station61
    4  station30
    
    N = 5
    sns.countplot(x='Station', 
                  data=df, 
                  palette="bright",
                  order=df['Station'].value_counts().index[:N])