Tony Wang Tony Wang - 1 month ago 7
Python Question

how to get return value of value_counts() in pandas with right order

just like code show below, I want to get the return values of value_counts() ,but c[i] just return the wrong order.so what's the best solution to get the value in right order

>>> type(c)
<class 'pandas.core.series.Series'>
>>> c
True 98
1479875 1
False 1
Name: 3000, dtype: int64
>>>
>>> c[0]
1
>>> c[1]
98
>>> c[2]
1
>>>

Answer

The problem stems from the mixed types serving as the index for the series. The value True is really 1, and the value False is really 0. So when you query c[0], it finds the value associated with c[False]. One fix might be to force True and False values to be stored as strings rather than booleans.

A better fix uses iloc.

>>> c.iloc[0]
98

How is the data generated, though? The integer mixed in with booleans is confusing. Is that supposed to be there?