Bode
Bode

Reputation: 529

dataframe grouping and sorting

I am new to pandas and have a dataframe,df

    Index         prt     Mb      
 2017-08-09       tt      0       
 2017-08-09       uu    140       
 2017-08-10       uu    200      
 2017-08-11       tt     0        
 2017-08-11       tt    150      
 2017-08-16       uu    200       

I want a dataframe like this

   Index          prt    Mb      ttt
 2017-08-10       uu    200     200/1000=0.2 
 2017-08-11       uu    200     200/1000=0.2
 2017-08-09       uu    140     140/1000=0.014                 
 2017-08-11       uu     0      0/10000=0 

the ttt column should be replaced with the result of the division by 1000.How can I go about it?

Upvotes: 0

Views: 73

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

I doubt you need groupby here

df= df.sort_values('Mb',ascending=False)
df['ttt'] = df['Mb'].div(1000)
# Based on the comment. `df['ttt'] = pd.to_numeric(df['Mb'],errors='coerce').div(1000)`

        Index prt   Mb   ttt
2  2017-08-10  uu  200  0.20
5  2017-08-16  uu  200  0.20
4  2017-08-11  tt  150  0.15
1  2017-08-09  uu  140  0.14
0  2017-08-09  tt    0  0.00
3  2017-08-11  tt    0  0.00

To remove the tt from the dataframe a simple boolean indexing would be enough i.e

df[df['prt'].eq('uu')] 

      Index   prt   Mb   ttt
2  2017-08-10  uu  200  0.20
5  2017-08-16  uu  200  0.20
1  2017-08-09  uu  140  0.14

Upvotes: 2

Related Questions