[英]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?在 python 中,如何在 CSV 文件中搜索某个关键字并在其后编辑单元格? 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.这是一个库存系统项目,我将在 CSV 文件中列出项目名称、数量和价格。
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?因此,例如,如果 CSV 文件显示以下示例,我想搜索玩具并编辑数量,我该怎么做?
[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.
仅从索引 1 开始,放入列表理解以消除任何空白。 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:如果您想编辑
book
价格,请执行以下操作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.