[英]How to apply case Insensitive filter
所以我有CSV1:
Name, City, Country
David, Los Angeles, US
Peter, Chicago, US
Mark, Chicago, US
Brian, New York, US
Paul, Los Angeles, US
Andy, Boston, US
Chris, Dallas, US
和CSV2:
City, Name, Country
PETER, Chicago, US
Adam, Florida, US
MARK, Chicago, US
James, Austin, US
BRIAN, New York, US
我想刪除多余的名稱。 城市和國家是什么並不重要,因為我只需要將名稱寫入輸出csv文件。 所以在這種情況下,對於BRIAN和brian,它將刪除冗余數據並只采用一個名稱(brian)。 同時,我希望將CSV1但不是CSV2的數據('Name')打印到輸出文件中。 所以,基本上,它是一個不區分大小寫的過濾器。 像這樣的東西:
Name:
David
Peter
Mark
Brian
Paul
Andy
Chris
我試過這段代碼:
import csv
# load second file as lookup table
data2 = {}
data1 = {}
with open('CSV2.csv', 'r') as csvinput:
reader = csv.reader(csvinput)
for row in csvinput:
data2[row[1]] = row
# now process first file against it
with open("CSV1.csv", 'r') as lookuplist:
reader1 = csv.reader(lookuplist)
for col in lookuplist:
data1[col[0]] = col
if col[0] not in data2:
print(col[0])
if col.lower()[0] == data2.lower()[1]:
print('Matches')
這是我得到的錯誤:
AttributeError: 'dict' object has no attribute 'lower'
我知道我正在創建的列表有問題但是我無法弄清楚它是否實際上比較了兩列的小寫並打印MATCHES,因為我想先驗證它。
一方面
if col.lower()[0] == data2.lower()[1]:
應該:
if col[0].lower() == data2[1].lower():
這就是導致錯誤的原因
AttributeError: 'dict' object has no attribute 'lower'
編輯
要解決注釋中提到的KeyError:
for k, v in data2:
if data2[k].lower() == col[0].lower():
print('Matches')
您也可以通過變量v(代表dict中的每個值)進行比較,但我使用了按鍵訪問索引以清楚該功能。
似乎沒有必要導入csv,因為您可以通過拆分逗號輕松提取信息。 此外,最好添加一個檢查,以便“名稱”不被視為有效名稱。
我不知道這是否是一個要求,但是你需要用第三個文件進行過濾,我更喜歡定義一個我們可以用參數調用的函數來立即構建一個未編輯的列表。
def build_unduped_names(names_repository, file_name):
with open(file_name) as csvinput:
for row in csvinput:
exploded_row = row.split(',')
if exploded_row[0].lower() == 'name':
continue
names_repository[exploded_row[0].lower()] = True
file_names = [
'CSV1.csv',
'CSV2.csv',
]
unduped = {}
for file_name in file_names:
build_unduped_names(unduped, file_name)
print(set(unduped))
嘗試這個:
csv1names = [(line.split()[0]).title() for line in csv1file]
csv2names = [(line.split()[0]).title() for line in csv2file]
filtered = [name if name not in csv2names for name in csv1names]
然后,您只需將filtered
的內容寫入您的文件即可。
import pandas as pd
df = pd.read_csv('location/filename.csv')
df['Name'] = df['Name'].apply(lambda x: x.capitalize())
print(df['Name'].unique()) #Now you will get all the unique names.
將這些名稱寫入所需的csv文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.