我正在研究一個簡單的資料過濾器,我需要幫助完成這項任務:
假設這是我的 .csv 檔案:
08534710,2888,15
08583315,2999,5
我的目標是撰寫一個函式來搜索給定值(例如 2888)并回傳它旁邊的值(15)這是我目前的代碼:
def wordfinder(searchstring):
csv_file = pd.read_csv('test.csv', "r")
for searchstring in csv_file:
if searchstring in csv_file:
print(searchstring[2])
return searchstring[2]
但我不認為它按預期作業。
uj5u.com熱心網友回復:
搜索searchstring第二列并回傳第三列的值:
def wordfinder(searchstring):
df = pd.read_csv('test.csv', dtype=str, header=None)
return df.loc[df[1] == searchstring, 2]
輸出:
>>> wordfinder('2888')
0 15
Name: 2, dtype: object
# OR
>>> wordfinder('2888').tolist()
['15']
uj5u.com熱心網友回復:
真的很簡單:
# Open and read the file
with open('t.txt') as f:
lines = [l.strip() for l in f.readlines()]
def get_field(num):
for line in lines:
parts = line.split(',')
if parts[1] == str(num):
return int(parts[2])
用法:
>>> get_field(2888)
15
>>> get_field(2999)
5
uj5u.com熱心網友回復:
我建議以下解決方案:
- 這只是一個簡單的搜索任務,這意味著您不需要資料框或匯入整個
pandas包;或者 - 你事先不知道你
searchstring出現在哪一欄。
import csv
def word_finder(search_string):
# Read the CSV file
csv_reader = csv.reader('test.csv')
# Loop through every line
for line in csv_reader:
# If the search_string exists in this line
if search_string in line:
# Get its position
position = line.index(search_string)
# Only take the next value if it exists
if position 1 < len(line):
return line[position 1]
# Not found
return None
uj5u.com熱心網友回復:
對于這樣一個簡單的情況,您實際上并不需要熊貓。嘗試這個:
search = '2888'
with open('my.csv') as csv:
for line in csv:
tokens = line.strip().split(',')
try:
i = tokens.index(search)
print(tokens[i 1])
except (ValueError, IndexError):
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352884.html
