Accessing first column of pandas value_counts

value_counts returns a Pandas Series:

df = pd.DataFrame(np.random.choice(list("abc"), size=10), columns = ["X"])
df["X"].value_counts()
Out[243]: 
c    4
b    3
a    3
Name: X, dtype: int64

For the array of individual values, you can use the index of the Series:

vl_list = df["X"].value_counts().index
Index(['c', 'b', 'a'], dtype='object')

It is of type "Index" but you can iterate over it:

for idx in vl_list:
    print(idx)

c
b
a

Or for the numpy array, you can use df["X"].value_counts().index.values


You can access the first column by using .keys() or index as below:

df.column_name.value_counts().keys()

df.column_name.value_counts().index


Use Panda's iteritems():

df = pd.DataFrame({'mycolumn': [1,2,2,2,3,3,4]})
for val, cnt in df.mycolumn.value_counts().iteritems():
    print 'value', val, 'was found', cnt, 'times'

value 2 was found 3 times
value 3 was found 2 times
value 4 was found 1 times
value 1 was found 1 times

Tags:

Python

Pandas