Jane Borges
Jane Borges

Reputation: 592

How to create a column on the dataframe from value_counts ()

I have the following dataframe:

       df = pd.DataFrame({'ID': ['4338', '4466', '1024',
                                 '4338', '4338', '5548'], 
                          'Instrument': ['temp_sensor', 'temp_sensor', 'temp_sensor',
                                         'strain_gauge', 'light_sensor',
                                         'strain gauge']})


                  print(df)

                   ID      Instrument
                  4338     temp_sensor
                  4466     temp_sensor
                  1024     temp_sensor
                  4338     strain_gauge
                  4338     light_sensor
                  5548     strain_gauge

I would like to count the column 'Instrument'. So I made the following code:

        Result = df['Instrument'].value_counts() / 2

        print(Result)

        temp_sensor     1.5
        strain_gauge    1.0
        light_sensor    0.5

The code is working. But I would like to assign it as a column on the dataframe.

The desired output would be:

                    ID     Instrument         Result
                  4338     temp_sensor        1.5
                  4466     temp_sensor        1.5
                  1024     temp_sensor        1.5
                  4338     strain_gauge       1.0
                  4338     light_sensor       0.5
                  5548     strain_gauge       1.0

Tkank you.

Upvotes: 1

Views: 47

Answers (1)

BENY
BENY

Reputation: 323226

Let us do transform

df.groupby('Instrument')['ID'].transform('count')/2
0    1.5
1    1.5
2    1.5
3    1.0
4    0.5
5    1.0
Name: ID, dtype: float64

Upvotes: 1

Related Questions