0

Here is my code:

df1.pivot_table(index=["Unit", "Grade"],values = ["Unit", "QTY","ORDER_NUM", "ORDER ID"], aggfunc={'Cost': 'sum' ,'QTY':'sum', "ORDER_NUM":'count',"ORDER ID":'count'})

I want to get a count of the unique order numbers and order id. Using 'count' is not giving me a unique count. How do i do this?

1

1 Answer 1

1

You can use 'nunique':

example input:

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})

processing:

pd.pivot_table(df,
               values=['D', 'E'],
               index=['A', 'B'],
               columns=['C'],
               aggfunc={'D': 'sum',
                        'E': 'nunique',   ### HERE
                        }
               )

output:

            D           E      
C       large small large small
A   B                          
bar one   4.0   5.0   1.0   1.0
    two   7.0   6.0   1.0   1.0
foo one   4.0   1.0   2.0   1.0
    two   NaN   6.0   NaN   2.0
Sign up to request clarification or add additional context in comments.

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.