2017-08-28 125 views
0

我有一個CSV文件具有以下標題:添加一個新列到CSV文件中使用python

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) 
+0

你有熊貓嗎? –

+0

@cᴏʟᴅsᴘᴇᴇᴅ是的,我剛安裝它。 – daquezada

+0

@cᴏʟᴅsᴘᴇᴇᴅ謝謝! – daquezada

回答

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') 
相關問題