How to store the information returned from the value_counts() function

Viewed 25

I have the following dataframe:

      import pandas as pd
      import numpy as np

      df_Station_Weather = pd.DataFrame({'ID': [102, 102, 558, 115, 115, 501, 501, 10, 10, 10, 10], 
                                         'Code_Instrument': ['SEN_wider1898', 'SEN_UV', 
                                                             'SEN_wider1898', 'SEN_wider1898', 
                                                             'SEN_rain1015', 'SEN_01', 'SEN_01', 
                                                             'SEN_AD', 'SEN_AD', 'SEN_AD', 
                                                             'SEN_AD']})

      print(df_Station_Weather)

      ID    Code_Instrument
      102   SEN_wider1898
      102   SEN_UV
      558   SEN_wider1898
      115   SEN_wider1898
      115   SEN_rain1015
      501   SEN_01
      501   SEN_01
      10    SEN_AD
      10    SEN_AD
      10    SEN_AD
      10    SEN_AD

I would like to count the number of specific Instruments. So, I did the following:

     list_Instrument = df_Station_Weather['Code_Instrument'].value_counts()

I would like to select only the bottom three of the count. So, I did the following:

      list_Instrument_2 = list_Instrument.head(3)

I need to create an array containing the name of the ID of the three largest. It is in this part that I am in doubt.

I tried to build the array with the code:

      array = np.array(list_Instrument_2)

However, this created array stores the count values, but I would like it to store the name of the Code_Instrument.

      #Output:
      print(array)
      > array([4, 3, 2], dtype=int64)

     # Desired output
     array([SEN_AD, SEN_wider1898, SEN_01]

Thank you.

3 Answers

Try this,

list_Instrument.head(3).index.values

array(['SEN_AD', 'SEN_wider1898', 'SEN_01'], dtype=object)

If you want the names:

print(list_Instrument.head(3).index)

Returns:

Index(['SEN_AD', 'SEN_wider1898', 'SEN_01'], dtype='object')

Or print them nicely with a for loop:

for name in list_Instrument.head(3).index:
    print(name)

To obtain:

SEN_AD
SEN_wider1898
SEN_01

Finally, to store them directly into a list:

res = print(list(list_Instrument.head(3).index))
print(res)

Will give:

['SEN_AD', 'SEN_wider1898', 'SEN_01']

I would suggest you use a Hashtable instead of an Array to save your counts of occurrences. U could use the Id of your Code_Instruments as the Hashtable Keys and the number of occurrences as the designated value. You can get the values you need afterwards with an index, with a key, or a value. Here is a link on how to use Hashtables: https://www.tutorialsteacher.com/csharp/csharp-hashtable

Related