< p >编辑:
我发现,当文件中的某些文本与实际数据的格式不一致时,这个错误就会出现。这通常是页眉或页脚信息(大于一行,所以skip_header不起作用),它们不会被与实际数据相同数量的逗号分隔(当使用read_csv时)。使用read_table使用一个制表符作为分隔符,可以避免用户当前的错误,但会引入其他错误
# use the first 2 lines of the file to detect separator
temp_lines = csv_file.readline() + '\n' + csv_file.readline()
dialect = csv.Sniffer().sniff(temp_lines, delimiters=';,')
# remember to go back to the start of the file for the next time it's read
csv_file.seek(0)
df = pd.read_csv(csv_file, sep=dialect.delimiter)
import csv
import pandas as pd
path = 'C:/FileLocation/'
file = 'filename.csv'
f = open(path+file,'rt')
reader = csv.reader(f)
#once contents are available, I then put them in a list
csv_list = []
for l in reader:
csv_list.append(l)
f.close()
#now pandas has no problem getting into a df
df = pd.DataFrame(csv_list)
usecols : list-like or callable, optional
Return a subset of the columns. If list-like, all elements must either
be positional (i.e. integer indices into the document columns) or
strings that correspond to column names provided either by the user in
names or inferred from the document header row(s). For example, a
valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar',
'baz']. Element order is ignored, so usecols=[0, 1] is the same as [1,
0]. To instantiate a DataFrame from data with element order preserved
use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for
columns in ['foo', 'bar'] order or pd.read_csv(data, usecols=['foo',
'bar'])[['bar', 'foo']] for ['bar', 'foo'] order.
import io
import pandas as pd
file = open(f'{file_path}/{file_name}', 'r')
content = file.read()
# change new line character from '\r\n' to '\n'
lines = content.replace('\r', '').split('\n')
# Remove the first and last 2 lines of the file
# StringIO can be considered as a file stored in memory
df = pd.read_csv(StringIO("\n".join(lines[2:-2])), header=None)
这个错误给出了解决问题“Expected 2 fields in line 3, saw 12”的线索,saw 12表示第二行长度为12,第一行长度为2。
当您有如下所示的数据时,如果您跳过行,那么大部分数据将被跳过
data = """1,2,3
1,2,3,4
1,2,3,4,5
1,2
1,2,3,4"""
如果您不想跳过任何行,请执行以下操作
#First lets find the maximum column for all the rows
with open("file_name.csv", 'r') as temp_f:
# get No of columns in each line
col_count = [ len(l.split(",")) for l in temp_f.readlines() ]
### Generate column names (names will be 0, 1, 2, ..., maximum columns - 1)
column_names = [i for i in range(max(col_count))]
import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8
data = pd.read_csv("file_name.csv",header = None,names=column_names )
import re
path = 'GOOG Key Ratios.csv'
try:
data = pd.read_csv(path)
except Exception as e:
val = re.findall('tokenizing.{1,100}\s*Expected\s*(\d{1,2})\s*',str(e),re.I)
data = pd.read_csv(path, skiprows=int(val[0])-1)
import pandas as pd
#Method 1
data = pd.read_csv('file1.csv', error_bad_lines=False)
#Note that this will cause the offending lines to be skipped.
#Method 2 using sep
data = pd.read_csv('file1.csv', sep='\t')