Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: inverse of value_counts function

What's a quick way to produce the inverse output of the value_counts function?

For example, if I have the following series:

1      24
2       2
3       1
4       2
5       3
6      12
7      21
8     204
9     400
10     71
11    160
Name: foo, dtype: float64

How can I concisely produce the following array?

numpy.array([1, 1, 1, ... , 2, 2, 3, 4, 4, 5, 5, 5, 6, ... ])
like image 990
Andrew Mao Avatar asked Feb 18 '16 21:02

Andrew Mao


People also ask

What does Value_counts return in pandas?

Return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.

What is the purpose of Value_counts () function in pandas?

The value_counts() method returns a Series containing the counts of unique values. This means, for any column in a dataframe, this method returns the count of unique entries in that column.

What is the difference between Value_counts and count in pandas?

count() should be used when you want to find the frequency of valid values present in columns with respect to specified col . . value_counts() should be used to find the frequencies of a series.


1 Answers

You can use np.repeat. If your Series is named s, it's possible to write:

np.repeat(s.index.values, s.values)

Here s.index.values are the values to repeat, and s.values specifies the number of times that each value should be repeated. The output is a 1D array.

like image 188
Alex Riley Avatar answered Oct 06 '22 09:10

Alex Riley