[英]How to iterate through two pandas columns
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
use DataFrame.itertuples()
method: 使用
DataFrame.itertuples()
方法:
for a, b in test.itertuples(index=False):
print a, b
You can use zip
(this is native in python 3, can be imported from itertools
as izip
in python 2.7): 你可以使用
zip
(这在python 3中是原生的,可以在python 2.7中作为izip
从itertools
导入):
for a,b in zip(test.a, test.b):
print(a,b)
for a,b in izip(test.a, test.b):
print a,b
Try, 尝试,
for i in test.index : print test['a'][i], test['b'][i]
to give you, 为你带来,
0 4
1 5
2 6
3 7
I'm still trying to learn pandas myself. 我还在努力学习大熊猫。
You can also use the .iterrows()
method, it returns the Index
and Series
per row: 您还可以使用
.iterrows()
方法,它返回每行的Index
和Series
:
test = DataFrame({'a':range(4),'b':range(4,8)})
for idx, series in test.iterrows():
print series['a'], series['b']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.