【问题标题】:How to iterate through two pandas columns如何遍历两个熊猫列
【发布时间】:2016-11-17 17:30:30
【问题描述】:
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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用DataFrame.itertuples()方法:

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

    【讨论】:

    • 如果您有很多列并且只想按名称迭代其中两个,您可以使用zip(test.a, test.b)。 (zip 在 python 3 中,from itertools import zip 在 python 2.7 中)
    • @drevicko 实际上在 python 2.7 中是from itertools import izip
    • @drevicko 超过 2 个呢?
    • @makewhite zip 需要尽可能多的迭代器,例如。对于 3 列 zip(test.a, test.b, test.c) 将为您提供元组 (a,b,c)
    【解决方案2】:

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

    python 3

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

    蟒蛇2

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

    【讨论】:

      【解决方案3】:

      试试,

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

      给你,

      0 4
      1 5
      2 6
      3 7
      

      【讨论】:

        【解决方案4】:

        我自己还在努力学习 pandas。

        您也可以使用.iterrows() 方法,它每行返回IndexSeries

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          • 2017-01-15
          • 2021-11-09
          • 2019-05-09
          • 1970-01-01
          • 1970-01-01
          • 2021-01-06
          相关资源
          最近更新 更多