[英]How do I find the row number for a specific item in a CSV file in Python?
[英]How do I find the corresponding name with ID number in CSV file?
(這是我關於 SO 的第一篇文章,所以如果格式不正確,請告訴我!)
我正在制作一個表格,當從 CSV 文件中給出一個 ID 號時,它會提取名稱,並且完全不知道從哪里開始。
示例數據:
身份證號 | 姓名 |
---|---|
1 | 約翰·多伊 |
2 | 簡·什莫 |
3 | 凱恩·弗 |
因此,如果我輸入 ID 號“1”,它將是 output “Jane Doe”
謝謝
使用DictReader
模塊中的csv
並創建數據字典:
import csv
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile)
data = {d['ID Number']: d['Name'] for d in list(reader)}
num = input('Input an ID Number: ')
print(data.get(num, 'Not found'))
Output:
Input an ID Number: 1
John Doe
我會根據子集來做到這一點。 首先以 pandas dataframe 的形式讀入數據:
import pandas as pd
df = pd.read_csv("<filename>.csv")
從這里您想通過 id 查詢您的 name 列,因此(例如)如果您想查找與 ID = 1 關聯的名稱:
result = df[df["ID Number"] == 1]]
您可以將 csv 加載到字典中,然后反復詢問用戶輸入:
file = open("example.csv", "r")
d = {}
for line in file:
split = line.strip().split(",")
d[split[0]] = split[1]
while True:
id = input("Please input an ID: ")
print(d[id])
Output:
Please input an ID: 1
Jane Doe
Please input an ID: 3
Kane Foe
Please input an ID: 2
Jane Shmoe
以下是有關如何使用 panda 進行操作的提示:
import pandas as pd
df = pd.read_csv('sample.csv')
user=df[df['ID Number']==2].iloc[0]
print(user.to_dict())
在這個例子中,我們正在尋找 id 為 2 的用戶。然后我們選擇找到的第一個項目。 下一步,我們將其轉換為字典並打印出來。
您可以使用不同的 function 在命令行界面中讀取,例如輸入( https://www.geeksforgeeks.org/taking-input-in-python/ )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.