简体   繁体   中英

In python, how can I search a CSV file for a certain keyword and edit a cell following that using pandas?

In python, how can I search a CSV file for a certain keyword and edit a cell following that? I am a bit of a novice with programming so it's likely I'm doing something obviously wrong

It's for an inventory system project and I will have a list of items with the item name, quantity, and price in a CSV file.

So, for example, if the CSV file shows the example below and I want to search for toy and edit the quantity how would I do that?

[Item_Name]    [Quantity]]   [Price]
[toy],             [8],       [10]
[book],            [32],       [5]

Here is what have so far

import csv
import pandas as pd
inventory_data = pd.read_csv('inventory_list_1.csv')
existing_item = input('What is the name of the item you would like to edit')
existing_quantity = input ('what is the new quantity')
inventory_data.loc[inventory_data.Item_Name == existing_item, 'Quantity'] = existing_quantity

Thank you for any help you can give me.

file = open('inventory_list_1.csv')
lines = file.readlines()
file.close()

# We're going to ignore the first line.
lines = [line.strip() for line in lines[1:]] 

It's called slicing a list. only from index 1 onwards, put in a list comprehention to eliminate any whitespace. Now that we have these lines, we can iterate over them:

for line in lines:
    toy_data = line.split(',')
    # the list will have 3 elements; item_name,qty,price
    item_name = toy_data[0].title()
    quantity = toy_data[1]
    price = toy_data[2]
    
    # now we can print a nice line
    print(f"We have {quantity} pieces of {toy_name} priced at {price}.")

If you want to edit the price of book just do this:

for line in lines:
    if line[0] == 'book':
        line[2] = 3

This is What I ended up doing

import pandas as pd
import csv
pd.set_option('expand_frame_repr', False)
inventory_data = pd.read_csv('inventory_list_1.csv')
existing_item = input('Enter the name of the existing product name')
new_quantity = input("Enter the new quantity for the product")
find_item = inventory_data['Item_Name'].astype(str).str.contains(existing_item)
inventory_data.loc[find_item,'Quantity'] = new_quantity
inventory_data.to_csv('inventory_list_1.csv', index=False, quoting=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM