【发布时间】: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