使用函数在数据框中添加行

Adding rows in dataframe with function

# new empty dataframe to fill
indexes_to_check = pd.DataFrame(columns=['index', 'reason'])

# function which should fill
def add_to_df(index, reason, source):
    for i in indexes:
        row = pd.DataFrame([[i, reason]], columns=['index', 'reason'])
        source = source.append(row)
    return source

# filling a dataframe to further check
add_to_df(df.query('total_images == 0').index, 'no photo', indexes_to_check)

问题: 如果我转换函数 add_to_df 作为结果,我会看到一个临时数据框 source 按我的意愿填充,但数据框 indexes_to_check(我想填充)仍然是空的。

我应该怎么做才能填充 indexes_to_check 而不是临时数据框?

# function which should fill
def add_to_df(index, reason, source):
for i in indexes:
    row = pd.DataFrame([[i, reason]], columns=['index', 'reason'])
    source = source.append(row)
return source

在这个函数中查看你的 for 循环,
只需将 for i in indexes : 替换为 for i in index :

你的错误很简单,你使用了其他参数。

您必须将循环更改为 for i in index: 以将函数分配给新对象 indexes_to_check = add_to_df(df.query('total_images == 0').index, 'no photo', indexes_to_check):

# new empty dataframe to fill
indexes_to_check = pd.DataFrame(columns=['index', 'reason'])

# function which should fill
def add_to_df(index, reason, source):
    for i in index:
        row = pd.DataFrame([[i, reason]], columns=['index', 'reason'])
        source = source.append(row)
    return source

# filling a dataframe to further check
indexes_to_check = add_to_df(df.query('total_images == 0').index, 'no photo', indexes_to_check)

你函数中的'source'是一个局部变量,'indexes_to_check'没有改变。