-1

I was just wondering is it possible to get the output of a pandas .value_counts() to be a new dataframe? It is typically output in a couple of columns looking like a table, but something like the following doesn't work:

new_df = df['col'].value_counts()

And a related question (which is in part why I want to do the above) is I am struggling with using the output of df['col'].value_counts(). If your data looks like this:

Num, Let
0,A
1,A
2,B

Then you can run

counts = df['Let'].value_counts()
print counts['A']

which prints 2. And I could assign this value of 2 to a variable, e.g. max_let=counts['A']. If I wanted to output the max I could also do something like counts.head(1) I believe. But what if I wanted to assign the string 'A' to a variable aswell (that is why I wanted the extra dataframe), is that possible? And is there a way to set max_let to take the value of whatever comes out without having to specify 'A' (as I can't seem to do it using counts.head(1)?

Hopefully that wasn't too convoluted.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ben
  • 13
  • 4

1 Answers1

1

You should using reset_index

new_df = df['col'].value_counts().reset_index()
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Expected output is something like: `A 2 B 1` I can set the new_df equal to this and print new_df, but whereas on a normal dataframe you can perfore things like print df.iat[0,0] to look at an element, I can't do that with my new_df (and it's being able to pull out the elements that I want to do). Just had a go with your `reset_index()` and still getting an error: `'function' object has no attribute 'iat'` when I try `new_df.iat[0,0]` (sorry I hit enter before I'd fully typed a response) – Ben Dec 16 '18 at 01:49
  • @Ben try reset_index as I listed – BENY Dec 16 '18 at 01:49
  • Oh wait, my mistake - that has worked! Thanks a lot – Ben Dec 16 '18 at 01:55
  • @Ben if this work would you like accept it ? check mark at the left – BENY Dec 16 '18 at 01:59