如何解决如何对一个csv文件进行排序,使其仅在文件中获得一行?
这是我的代码的样子
pd.set_option('expand_frame_repr',False)
inventory_data = pd.read_csv('inventory_list_1.csv')
search_item = input('Enter the name of the item your looking for')
find_item = inventory_data['Item_Name'].astype(str).str.contains(serch_item)
print (find_item)
inventory_data.to_csv('inventory_list_1.csv',index=False,quoting=1)
这是CSV文件的示例,其中第一行是标题
[ITEM NAME 1],[QUANTITY 1],[PRICE 1]
pencil 3 4
pen 5 5
我希望能够输入笔
search_item = input('Enter the name of the item your looking for')
并返回以下行
pen 5 5
我有点不知所措
解决方法
您可以使用行函数并进行迭代
就是这样
for index,row in df.iterrows():
print(row['c1'],row['c2'])
Output:
10 100
11 110
12 120
来源: How to iterate over rows in a DataFrame in Pandas
,使用此
for (row,rowSeries) in inventory_data.iterrows():
print(row,rowSeries)
,
这是一个示例程序,用于读取csv文件的内容并检查项目。
inventory_list_1.csv
item,quantity,price
pencil,5,10
pen,5`
示例程序
# import csv module
import csv
# Ask for user input
search_item = input('Enter the name of the item your looking for: ')
# read data from csv file
filePointer = open('inventory_list_1.csv')
input_file = csv.DictReader(filePointer)
# set a flag
found = False
# iterate through the contents and check for search_item
for row in input_file:
if row['item'] == search_item:
print(row['item'],row['quantity'],row['price'])
found = True
break
if not found:
print(f"Item '{search_item}'' not found!")
# release
filePointer.close()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。