![](/img/trans.png)
[英]Retrieve specific rows of CSV file containing a particular keyword in Python
[英]Python retrieve specific rows from a csv file
我正在嘗試從csv文件中檢索特定的行,而不是從它們中創建一個新的csv文件。 我要檢索的行必須包含與列表相同的值。
myList=[HELLO, WORLD, DAD]
csv_file= doc_01 | doc_02 | doc_03 | doc_04 |
HELLO| 0,002 | 0,8 | 00,5 | 0,003 |
WORLD| 0,1 | 00,9 | 1,2 | 2,1 |
MOM | 00,3 | 00,7 | 0,22 | 0,55 |
我的意圖是遍歷該列表,如果列表中的值在csv的第一列中,則我要占用所有對應的行。
結果應為:
new_csv= doc_01 | doc_02 | doc_03 | doc_04 |
HELLO| 0,002 | 0,8 | 00,5 | 0,003 |
WORLD| 0,1 | 00,9 | 1,2 | 2,1 |
有辦法嗎?
您需要指定定界符='|' 當您讀取數據時
import pandas as pd
import csv
df= pd.read_csv('C:\Users\shmathew\Desktop\Sample\sample.txt',sep='|')
myList=['HELLO', 'WORLD', 'DAD']
print df[df['doc_01'].isin(myList)]
要么
infile=open('C:\Users\shmathew\Desktop\Sample\sample.txt', 'rb')
csv_reader = csv.reader(infile,delimiter='|')
for row in csv_reader:
if row[0] in myList :
print (row)
創建相同的輸出
doc_01 doc_02 doc_03 doc_04 doc_05
0 HELLO 0,002 0,8 00,5 0,003
1 WORLD 0,1 00,9 1,2 2,1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.