【问题标题】:How to iterate Pandas DataFrame (row-by-row) that has non-sequential index labels?如何迭代具有非顺序索引标签的 Pandas DataFrame(逐行)?
【发布时间】:2018-05-30 03:18:45
【问题描述】:

我正在尝试迭代具有 非顺序 索引标签的 Pandas DataFrame(逐行)。换句话说,一个 Dataframe 的索引标签如下所示:2,3,4,5,6,7,8,9,11,12,...。没有行/索引标签10。我想迭代 DataFrame 以根据条件更新/编辑每行中的某些值,因为我正在将 Excel 工作表(已合并单元格)读取到 DataFrames 中。

我尝试使用以下代码 (@ Manuel's answer) 来遍历 df 的每一行,并在条件适用时编辑每一行。

    for col in list(df): #All columns 
       for row in df[1].iterrows(): ##All rows, except first   
           if pd.isnull(df.loc[row[0],'Album_Name']): ##If this cell is empty all in the same row too.
               continue  
           elif pd.isnull(df.loc[row[0], col]) and pd.isnull(df.loc[row[0]+1, col]):  ##If a cell and next one are empty, take previous value.
               df.loc[row[0], col] = df.loc[row[0]-1, col]  

但是,由于 DataFrame 具有非顺序索引标签,我收到以下错误消息:KeyError: the label [10] is not in the [index]如何使用非顺序索引标签迭代和编辑 DataFrame(逐行)?

作为参考,这是我的 Excel 工作表和 DataFrame 的样子:

【问题讨论】:

  • 它是多索引

标签: python excel python-3.x pandas


【解决方案1】:

是的,只需将第二个循环更改为:

for row in df:

然后用“行”而不是名称来引用行。

 for col in df: #All columns 
       for row in df: ##All rows, except first   
           if row==1:
                continue #this skips to next loop iteration
           if pd.isnull(df.loc[row[0],'Album_Name']): ##If this cell is empty all in the same row too.
               continue  
           elif pd.isnull(df.loc[row[0], col]) and pd.isnull(df.loc[row[0]+1, col]):  ##If a cell and next one are empty, take previous value.
               df.loc[row[0], col] = df.loc[row[0]-1, col]  

【讨论】:

  • 如果这不起作用,请制作一个可重现的示例,这将使您的问题更加清晰。关于如何做到这一点的很好的说明在这里:stackoverflow.com/questions/20109391/…
  • @ EHB - 我对您代码中的缩进感到困惑。第一个 continue 是否与第二个 if 循环对齐?
猜你喜欢
  • 2019-06-16
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多