我编写了一个函数,该函数读取 csv 文件、执行一些计算并将输出写入同一文件。要将计算值附加到新列,我使用 df.at[index, column_name] = value
。
这是我的代码
def total_calc(n):
input = pd.read_csv(file_name)
input['calc'] = 0.0
for index, row in input.iterrows():
# perform calculations
input.at[index, 'calc'] = calc_value
input.to_csv(file_name, index=False)
当我将该函数用于 n 的多个值时,它会在同一列中写入值,从而覆盖数据帧中前 n 个值的值。
我尝试在函数中使用 i 并给出 index+i
,如下所示:
def total_calc(i,n):
input = pd.read_csv(file_name)
input['calc'] = 0.0
for index, row in input.iterrows():
# perform calculations
input.at[index+i, 'calc'] = calc_value
input.to_csv(file_name, index=False)
total_calc(1,2)
total_calc(2,8)
但是,列值仍然被覆盖。有没有办法将函数中多个值的列写入同一个文件而不覆盖?
所以这些是我当前的数据集列
names values wickets score
运行所有必需的功能后我需要这个
names values wickets score calc calc1 calc2
最佳答案
我认为您需要按范围
进行循环,并将值k
添加到列名称中 - 每个循环都会创建另一列:
def total_calc(i,n):
for k in range(n):
input = pd.read_csv(file_name)
input['calc' + str(i)] = 0.0
for index, row in input.iterrows():
# perform calculations
input.at[index, 'calc' + str(i)] = calc_value
input.to_csv(file_name, index=False)
关于python - 使用 df.at 时覆盖列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48906155/