【问题标题】:Python For Loop not iterating entire DataframePython For Loop没有迭代整个数据框
【发布时间】:2019-02-09 02:26:44
【问题描述】:

我正在尝试遍历整个 Python Pandas DataFrame ,但它似乎并没有遍历整个 DataFrame。它适用于长度较短的 DataFrame,但不适用于这个。另外,我在 Jupyter Notebook 工作。

我添加了一些打印语句来尝试调试。

def dropNotIn(df):

    print(df.shape)

    removedlist = []
    droplist = []

    for i, x in df.iterrows():
        rownum = i

    print(rownum)
    print(len(df))

dropNotIn(df) 的结果:

(59610, 9)
3449 --> Expected to be 59610
59610

这是我的 df.head():

    date    attendance  venue_city  venue_state venue_name  away_team   home_team   away_points home_points
9   2015-12-13  1740.0  Chicago IL  McGrath-Phillips Arena  Arkansas-Little Rock    DePaul  66  44
13  2015-11-22  0.0 St. Thomas  NaN Virgin Islands Sport & Fitness Center   Tulsa   Indiana State   67  59
14  2014-12-04  3469.0  St. Bonaventure NY  Reilly Center   Buffalo St. Bonaventure 63  72
21  2015-11-20  1522.0  St. Thomas  NaN Virgin Islands Sport & Fitness Center   Hofstra Florida State   82  77
24  2014-11-23  NaN St. Thomas  NaN Virgin Islands Sport & Fitness Center   Gardner-Webb    Seton Hall  67  85

【问题讨论】:

  • 你必须分享一个有代表性的数据样本。
  • @pyeR_biz,已添加。
  • 期望 3469,我没有看到您在 DataFrame 的所需输出中提到的其他值。您想要的输出需要匹配哪些条件?
  • @hemanta,我再次编辑了我的问题以排除条件。我想我的问题实际上不需要包含 if 语句。
  • 我正在尝试遍历整个 df。每次通过循环,我设置rownum = i,但最后,当我打印rownum时,它与df的大小/长度不匹配。

标签: python pandas loops dataframe for-loop


【解决方案1】:

在 pandas 中,DataFrame.iterrows() 产生 index 和行。索引是您可以控制的,而查看您的样本数据,您并没有密集整数的索引,而是其他东西。

试试这个代码:

def dropNotIn(df):

    print(df.shape)

    removedlist = []
    droplist = []

    num_rows = 0
    for i, x in df.iterrows():
        num_rows += 1

    print(num_rows)
    print(len(df))

这会显式计算行数,而不是尝试使用索引。如果您真的想在操作期间计算行数,我建议您使用内置函数enumerate

for num, (index, row) in enumerate(df.iterrows()):
   pass

但是,我怀疑您可能不想这样做,因为当您使用数据框执行操作时,您希望尽可能地将它们矢量化。

【讨论】:

    【解决方案2】:

    iterrow 围绕不等于 rownum 的索引进行迭代。您的某些索引可能不止一行。

    尝试解压 x,y = df.shape() 并围绕 range(x) 进行迭代

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      相关资源
      最近更新 更多