【问题标题】:CSV import and manipulation in PythonPython 中的 CSV 导入和操作
【发布时间】:2018-08-16 05:46:09
【问题描述】:

我是 Python 新手,正在尝试获取包含以下内容的 CSV 文件:

Computers,price
comp1,150
comp2,250
comp3,100
comp4,175
comp5,60

我正在尝试读取这些数据(使用导入 CSV 模块),然后我想删除任何价格低于 125 的计算机,然后我想添加一个名为 quality 的列。 对于剩余的计算机,我想根据以下内容将新列中的数据设置为高或平均

if price is <= 175 
    the price = average 
    else price = High

这是我目前所拥有的:

#python 3.7

# Program to read input and out a new file with changes based on conditions

import csv

  with open('c:\computers.csv', 'r') as input, open('output.csv', 'wb') as 
      output:
      csv_input = csv.reader(input)
      csv_output = csv.writer(output, lineterminator='\n')

# keep only computers 125 or over

csv_output.writerow(next(csv_input))

for cols in csv_input:
  if float(cols[2]) <=125:
    csv_output.writerows(cols)

#Create new Column called Quality

headers = reader.next()
headers.append('Quality')
writer.writerow(headers)

# Check price and set Quality Column to Average if price <= 175 otherwise set to High

这是我目前所处的位置。我想我需要做一个 if else 但不确定如何让它查找价格列,如果它是

再说一次,我是新人,所以我希望我不会在这里受到太多的抨击。

感谢任何帮助。

谢谢

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    我猜你想要:

    for cols in csv_input:
      if float(cols[2]) >125:
        if float(cols[2]) >175:
          cols[3]='High'
        else:
          cols[3]='Average'
        csv_output.writerows(cols)
    

    将标题部分放在此之前

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      相关资源
      最近更新 更多