【发布时间】:2020-10-31 14:49:40
【问题描述】:
我有一系列非常脏的 CSV 文件。
它们看起来像这样:
,"File Inputs",,,,,,,,,,,"Email Category",,"Contact Info Category",
RecCtr,Attom_ID,PeopleID,"First Name","Last Name",AddressFullStreet,City,State,Zip," ","Individual Level Match"," ","Email Address"," ",Phone,"Phone Type"
1,19536969,80209511,ANTHONY1,MACCA1,"123 Main RD","Anytown",MA,12345
2,169874349,80707224,ANTHONY2,MACCA2,"123 Main RD","Anytown",MA,12345
3,1057347,81837554,ANTHONY3,MACCA3,"123 Main RD","Anytown",MA,12345
4,36946575,81869227,ANTHONY3,MACCA4,"123 Main RD","Anytown",MA,12345,,YES,,,,1234567890,Mobile
正如您在上面看到的,有 16 个元素。第 1,2,3 行不好,第 4 行很好。
我正在使用这段代码来尝试阅读它们。
df = pd.read_csv(file, skiprows=2, dtype=str, header=None)
df.columns = ['RecCtr', 'Attom_ID', 'PeopleID', 'First_Name', 'Last_Name', 'AddressFullStreet', 'City', 'State', 'Zip', 'blank1', 'Individual_Level_Match', 'blank2', 'Email_Address', 'blank3', 'Phone', 'Phone_Type'
]
df = df.replace({pd.np.nan: None})
我的问题是我不知道如何告诉系统我有 16 个元素,应该跳过任何不是 16 个元素的行。
我的代码中的第 1 行似乎强制第 1-3 行是好的,然后第 4 行变得不好。
我如何指定有多少列,以便将第 1 行视为错误而跳过。和其他人一起。
谢谢
更改 1:
headers = ['RecCtr', 'Attom_ID', 'PeopleID', 'First_Name', 'Last_Name', 'AddressFullStreet', 'City', 'State', 'Zip', 'blank1', 'Individual_Level_Match', 'blank2', 'Email_Address', 'blank3', 'Phone', 'Phone_Type']
df = pd.read_csv(file, skiprows=2, dtype=str, header=headers)
回复:
raise ValueError("header must be integer or list of integers")
ValueError: header must be integer or list of integers
【问题讨论】: