繁体   English   中英

如何迭代具有非顺序索引标签的Pandas DataFrame(逐行)?

[英]How to iterate Pandas DataFrame (row-by-row) that has non-sequential index labels?

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

我尝试了以下代码(@ Manuel的答案 )来遍历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的外观:

并排捕获

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

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]  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM