如何遍历两个pandas列

dmv*_*nna 16 python pandas

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
Run Code Online (Sandbox Code Playgroud)

HYR*_*YRY 25

使用DataFrame.itertuples()方法:

for a, b in test.itertuples(index=False):
    print a, b
Run Code Online (Sandbox Code Playgroud)

  • 如果你有很多列,并且想要按名称迭代其中的两个,你可以使用`zip(test.a,test.b)`.(`python 3中的`zip`,`来自python 2.7中的itertools import zip`) (3认同)

dre*_*cko 11

您可以使用zip(这是蟒蛇3人,可以从进口itertoolsizip在Python 2.7):

蟒蛇3

for a,b in zip(test.a, test.b): 
    print(a,b)                          
Run Code Online (Sandbox Code Playgroud)

python 2

for a,b in izip(test.a, test.b): 
    print a,b                                 
Run Code Online (Sandbox Code Playgroud)


mon*_*kut 8

您还可以使用.iterrows()方法。它返回IndexSeries每行:

test = DataFrame({'a':range(4),'b':range(4,8)})
for idx, series in test.iterrows():
    print series['a'], series['b']
Run Code Online (Sandbox Code Playgroud)


nit*_*tin 6

尝试,

for i in test.index : print test['a'][i], test['b'][i]
Run Code Online (Sandbox Code Playgroud)

为你带来,

0 4
1 5
2 6
3 7
Run Code Online (Sandbox Code Playgroud)