Python Pandas:按系列打印名称和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30523521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:35:48  来源:igfitidea点击:

Pandas: Printing the Names and Values in a Series

pythondatabasepython-3.xpandas

提问by Meghdeep Ray

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 :

它给我列 A 的列值,然后是它旁边的分组的大小。使用 w ( a Series ),如何单独打印分组的名称?分组的值可以通过以下方式获得:

for i in w :
    print(i)

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

但我不知道如何获得这些名字。

采纳答案by Zero

You can iterate over series using iteritems()

您可以使用迭代系列 iteritems()

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

where, indexhas column names, and valvalue/size

其中,index有列名和val值/大小

回答by Ami Tavory

The indexmember of a series is the "names", so:

index系列的成员是“名称”,因此:

for name, val in w.index:
    print name

will iterate over the names. For both, you can use

将遍历名称。对于两者,您都可以使用

import itertools

for name, val in itertools.izip(w.index, w):
    print name, val

回答by EdChum

In python 3 the following works fine:

在python 3中,以下工作正常:

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:

就像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

但是,可移植的方法(也适用于 python 2)是使用 iteritems