python - 使用 df.at 时覆盖列值

标签 python python-3.x pandas

我编写了一个函数,该函数读取 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/

相关文章:

python - 多对多的嵌套序列化器

python - Pandas 时间序列图设置 x 轴主要和次要刻度和标签

python - 在Python中对数据进行分类

python - 如何使 Pyre-check 库与 numpy 一起工作?

python-3.x - 从带有图像的扫描pdf中提取文本?

python - 创建子图而不是单独的图

Python:替换项目

python - Output 类型的对象不可 JSON 序列化

python - 通过使用密集层作为最后一层来卡住 TensorFlow

python - Python 中 '\0\0' 的含义?