vinay karagod
vinay karagod

Reputation: 254

Converting R code into python code

working code in R

library(dplyr)
tmp <- test %>% 
       group_by(InvoiceDocNumber) %>% 
       summarise(invoiceprob=max(itemprob)) %>% 
       mutate(invoicerank=rank(desc(invoiceprob)))

But I want to rewrite the code in python. I wrote the below code but it's throwing me the error. I am using the similar version of dplyr which is available in python.

from dfply import *
tmp = (test >>
       group_by(test.InvoiceDocNumber) >> 
       summarize(invoiceprob=max(test.itemprob)) >>
       mutate(invoicerank=rankdata(test.invoiceprob)))

AttributeError: 'DataFrame' object has no attribute 'invoiceprob'

Can anyone help me ?

Upvotes: 4

Views: 13653

Answers (3)

Panwen Wang
Panwen Wang

Reputation: 3825

You would like to use: datar (I am the author)

from datar.all import *

tmp = test >> \
      group_by(f.InvoiceDocNumber) >> \
      summarise(invoiceprob=max(f.itemprob)) >> \
      mutate(invoicerank=rank(desc(f.invoiceprob)))

Upvotes: 0

andrew_reece
andrew_reece

Reputation: 21264

You can use assign to get it all in one chain:

(
test.groupby("InvoiceDocNumber", as_index=False)
 .itemprob.max()
 .rename(columns={"itemprob":"invoiceprob"})
 .assign(invoicerank = lambda x: x.invoiceprob.rank(ascending=False))
)

Output:

   InvoiceDocNumber  invoiceprob  invoicerank
0                 0     0.924193          5.0
1                 1     0.974173          4.0
2                 2     0.978962          3.0
3                 3     0.992663          2.0
4                 4     0.994243          1.0

Data:

import numpy as np
import pandas as pd
n = 100
test = pd.DataFrame({"InvoiceDocNumber": np.random.choice(np.arange(5), size=n),
                     "itemprob": np.random.uniform(size=n)})

Upvotes: 3

vinay karagod
vinay karagod

Reputation: 254

I got the answer

ddd = test.groupby('InvoiceDocNumber', as_index=False).agg({"itemprob": "max"})
ddd= ddd.rename(columns={'itemprob': 'invoiceprob'})
ddd['invoicerank'] =ddd['invoiceprob'].rank(ascending=0)

Upvotes: 0

Related Questions