【问题标题】:How to add to a entire column in CSV (Excel)如何在 CSV (Excel) 中添加到整个列
【发布时间】:2021-03-16 01:41:30
【问题描述】:

我是 Python 新手,我有这个 CSV 文件。

我需要向帐户中添加 10 美元。我需要添加的余额在 D 列中。我该怎么做。

我无法使用 pandas。

然后我需要将它保存到不同名称的不同文件中。

【问题讨论】:

  • 这个问题能回答你的问题吗:stackoverflow.com/questions/55404141/…
  • 使用 csv 模块读写文件。一次将一行读入列表。将 10 添加到列表的“列索引”。使用 csv 模块将更新后的列表写入输出文件。

标签: python csv


【解决方案1】:
import csv

# read rows
rows = []
with open('file.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')
    for row in reader:
        rows.append(row)

# add the value
for row in rows:
    row["Balance"] = float(row["Balance"]) + 10

# write csv back
with open("new.csv", "w", newline='') as outfile:
    writer = csv.DictWriter(outfile, fieldnames=list(rows[0]))
    writer.writeheader()
    writer.writerows(rows)

我也在加pandas方式,以后可能会用到。

import pandas as pd
df = pd.read_csv("file.csv", index_col=0, delimiter = ",")
df["Balance"] += 10
df.to_csv("new.csv", sep=',')

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2015-11-29
    • 2012-06-19
    • 2013-07-25
    • 2020-10-14
    相关资源
    最近更新 更多