0

I tried to rename the column that has been obtained as the result of groupby & count operation like below:

dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()
print(dfa[:1])

the output obtained is

 Product_ID     0
0  P00000142  1130

The column names are not what I specified. So I changed it again using the below command

dfa.columns =['product','sales']
print(dfa[:1])

 product  sales
0  P00000142   1130

Then I got the expected column names. However I believe it shall be obtained during the first method dataframe.rename itself. What is wrong in the 1st code snippet dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()that I did not get the expected output.

3
  • 1
    do you need df.groupby('Product_ID').size().reset_index(name='sales_count') ? Commented May 29, 2019 at 5:18
  • df.groupby('Product_ID').Product_ID.count() will result in a series, not a dataframe. Your output, however, is a dataframe. It seems that your code is not quite correct, or else the output looks to be inconsistent. Commented May 29, 2019 at 5:24
  • @anky_91: that worked ! thanks Commented May 29, 2019 at 5:25

1 Answer 1

2

As mentioned in comments, you need:

df.groupby('Product_ID').size().reset_index(name='sales_count')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.