1

I would like to change index[3] for all items by 10% of it's current value.

Anything I have found online has not produced any results. The closest result is below but I couldn't see how to implement.

for line in finalList:
    price = line[3]
    line[3] = float(line[3]) * 1.1
    line[3] = round(line[3], 2)
    print(line[3])

My products.csv looks like so:

Hardware,Hammer,10,10.99
Hardware,Wrench,12,5.75
Food,Beans,32,1.99
Paper,Plates,100,2.59

My code:


def getProductsData():
    productsfile = open('products.csv', 'r')
    # read products file
    productsreader = csv.reader(productsfile)
    products = []

    # break each line apart (unsure of meaning here)
    for row in productsreader:
        for column in row:
            print(column, end = '|')
        # create and append list of the above data within a larger list
        products.append(row)

        # loop through the list and display it's contents
        print()

    # add 10% to price    


    # add another product to your list of lists   
    products.append(['Toddler', 'Millie', '2017', '8.25'])
    print(products)

    # write the contents to a new file
    updatedfile = open('updated_products.csv', 'w')

    for line in products:
        updatedfile.write(','.join(line))
        updatedfile.write(','.join('\n'))
    updatedfile.close()

getProductsData()
Genoxidus
  • 51
  • 1
  • 6
  • 2
    What are you having trouble with: getting the value to change? Computing the new value? Replacing the old value with the new? – Scott Hunter Aug 09 '20 at 23:14
  • Possibly related: [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int), [Change specific value in CSV file via Python](https://stackoverflow.com/questions/11033590/change-specific-value-in-csv-file-via-python) – wwii Aug 09 '20 at 23:23
  • If any of these answers helped you, please accept one so people can find the correct answer more easily. – M-Chen-3 Nov 26 '20 at 00:56

1 Answers1

0

To add 10% to price, you would first need to make sure the column type is numeric and then you can carry out the calculation.

df:

Hardware,Hammer,10,10.99
Hardware,Wrench,12,5.75
Food,Beans,32,1.99
Paper,Plates,100,2.59

Make sure column is numeric:

df[3]=pd.to_numeric(df[3])

Overwrite column with 10% added to values, and round to 2 decimal places:

df[3]=round(df[3]+(df[3]/10),2)

df:

          0       1    2      3
0  Hardware  Hammer   10  12.09
1  Hardware  Wrench   12   6.32
2      Food   Beans   32   2.19
3     Paper  Plates  100   2.85