1

I want to call df['item'].value_counts() and, with minimal manipulation, end up with a dataframe with columns item and count.

I can do something like this:

df['item'].value_counts().reset_index().rename(columns={"item":"count", "index": "item"})

... which is fine but I'm like 95% sure there is a cleaner way to do this by passing a variable to reset_index or something similar

3 Answers 3

2

Let us try with groupby

df.groupby('item')['item'].count().reset_index(name='count')
1
  • Did not realize that reset_index had a name parameter! Commented Nov 18, 2022 at 2:58
2

Using set_axis is very slightly cleaner.

df['item'].value_counts().reset_index().set_axis(['item','count'], axis=1)
1

Using groupby, value_counts, and to_frame

import pandas as pd  # 1.5.1


df = pd.DataFrame({"item": list("aaabbbbbbccc")})

counts = df.groupby("item").value_counts().to_frame("count").reset_index()

print(counts)
  item  count
0    a      3
1    b      6
2    c      3

using value_counts and to_frame

counts = df["item"].value_counts().to_frame("count").reset_index(names="item")

print(counts)
  item  count
0    a      3
1    b      6
2    c      3

References

to_frame

df.reset_index calls for parameter names vs name in pd.Series.reset_index

2
  • 1
    index should be item :-)
    – BENY
    Commented Nov 18, 2022 at 2:44
  • Ah , happy coding ~
    – BENY
    Commented Nov 18, 2022 at 2:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.