4

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 ?

3 Answers 3

3

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)})
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.