Python 如何遍历两个熊猫列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15125343/
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
How to iterate through two pandas columns
提问by dmvianna
In [35]: test = pd.DataFrame({'a':range(4),'b':range(4,8)})
In [36]: test
Out[36]:
a b
0 0 4
1 1 5
2 2 6
3 3 7
In [37]: for i in test['a']:
....: print i
....:
0
1
2
3
In [38]: for i,j in test:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: need more than 1 value to unpack
In [39]: for i,j in test[['a','b']]:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: need more than 1 value to unpack
In [40]: for i,j in [test['a'],test['b']]:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: too many values to unpack
采纳答案by HYRY
use DataFrame.itertuples()method:
使用DataFrame.itertuples()方法:
for a, b in test.itertuples(index=False):
print a, b
回答by nitin
Try,
尝试,
for i in test.index : print test['a'][i], test['b'][i]
to give you,
为你带来,
0 4
1 5
2 6
3 7
回答by monkut
I'm still trying to learn pandas myself.
我仍在尝试自己学习熊猫。
You can also use the .iterrows()method, it returns the Indexand Seriesper row:
您还可以使用该.iterrows()方法,它返回每行的Index和Series:
test = DataFrame({'a':range(4),'b':range(4,8)})
for idx, series in test.iterrows():
print series['a'], series['b']
回答by drevicko
You can use zip(this is native in python 3, can be imported from itertoolsas izipin python 2.7):
您可以使用zip(这是蟒蛇3人,可以从进口itertools为izip在Python 2.7):
python 3
蟒蛇 3
for a,b in zip(test.a, test.b):
print(a,b)
python 2
蟒蛇2
for a,b in izip(test.a, test.b):
print a,b

