使用python将新列添加到CSV文件

时间:2017-08-28 18:09:37

标签: python python-3.x pandas csv

我有一个CSV文件,其中包含以下标题:

model ,years ,engine ,power_kW,power_hp,torque_Nm,torque_ft-lb,0-100 km/h

我想写下面的列表:

power_hp = [113.99, 120.69, 127.4, 134.1, 140.81, 147.51, 154.22, 167.63, 170.31, 174.33, 199.81, 214.56, 214.56, 230.66, 254.79, 268.2, 301.73, 301.73, 321.84, 414.38, 443.88]

进入power_hp列。

我的代码如下:

import csv
import shutil
import unit_converter


shutil.copy('bmw_e90_in.csv', 'bmw_e90_out.csv')

path = 'bmw_e90_out.csv'
file = open(path, newline='')
reader = csv.reader(file)
header_row = next(reader)       # First line in header

power_hp = []
torque_ft_lb = []
# row = [Model, Years, Engine, Power_kW, Power_hp, Torque_Nm, Torque_ft-lb,
# 0-100 km/h]
for row in reader:
    power_kw = float(row[3])
    torque_nm = float(row[5])

    power_hp.append(unit_converter.power(power_kw))
    torque_ft_lb.append(unit_converter.torque(torque_nm))

print(power_hp)

# compute an store power and torque values
return_path = 'bmw_e90_out.csv'
file = open(return_path, 'w', newline='')
writer = csv.writer(file)

1 个答案:

答案 0 :(得分:0)

使用pandas,使用pd.read_csv加载数据框,添加新列,然后使用df.to_csv写入同一文件。

import pandas as pd

power_hp = [113.99, 120.69, 127.4, 134.1, 140.81, 147.51, 154.22, 167.63, 170.31, 174.33, 199.81, 214.56, 214.56, 230.66, 254.79, 268.2, 301.73, 301.73, 321.84, 414.38, 443.88]

df = pd.read_csv('bmw_e90_out.csv')
df['power_hp'] = power_hp

df.to_csv('bmw_e90_out.csv')