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

问题描述 投票:0回答:1
# 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)

问题:如果我投一个函数 如果我投一个函数 添加到df 结果我看到一个临时的数据框架 源头 我想怎么填就怎么填,但数据框 要检查的索引 (我希望被填充)仍然是空的。

我应该怎么做才能填满 要检查的索引 但不是临时数据框?

python pandas dataframe fill
1个回答
0
投票

你必须把这个循环改成 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)

0
投票
# 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 Loop,只需将其替换为 for i in indexes :for i in index :

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.