如何遍历两个pandas列

2024-04-20 14:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: intestmostforipythonlinecallconsole
3条回答

使用DataFrame.itertuples()方法:

for a, b in test.itertuples(index=False):
    print a, b

试试看

for i in test.index : print test['a'][i], test['b'][i]

给你

0 4
1 5
2 6
3 7

您可以使用zip(这是python 3的本机代码,可以从itertools导入为izip在python 2.7中):

Python3

for a,b in zip(test.a, test.b): 
    print(a,b)                          

Python2

for a,b in izip(test.a, test.b): 
    print a,b                                 

相关问题 更多 >