如何对一个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()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...