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
Pandas: Printing the Names and Values in a Series
提问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, index
has column names, and val
value/size
其中,index
有列名和val
值/大小
回答by Ami Tavory
回答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