Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Printing the Names and Values in a Series

When I use :

w = y.groupby['A'].size()

It gives me the column values of Column A and then the size of the grouping beside it. Using w ( a Series ), how do I print separately the names of the groupings ? The values of the grouping can be gotten via :

for i in w :
    print(i)

But I can't figure out how to get the names.

like image 712
Meghdeep Ray Avatar asked May 29 '15 07:05

Meghdeep Ray


Video Answer


2 Answers

You can iterate over series using iteritems()

In [100]: for index, val in w.iteritems():
   .....:     print index, val
   .....:

where, index has column names, and val value/size

like image 110
Zero Avatar answered Oct 26 '22 19:10

Zero


In python 3 the following works fine:

In [31]:
df = pd.DataFrame({"A":["a","b","c","a"]})
w = df.groupby('A').size()
w

Out[31]:
A
a    2
b    1
c    1
dtype: int64

In [61]:
for i,r in w.items():
    print(i,r)
​
a 2
b 1
c 1

As does iterkv:

In [62]:
for i,r in w.iterkv():
    print(i,r)
a 2
b 1
c 1

However, the portable method (will work in python 2 also) is to use iteritems

like image 22
EdChum Avatar answered Oct 26 '22 19:10

EdChum