df = pd.read_csv('somefile.csv')

...给出一个错误:

熊猫…/网站/ / io / parsers.py: 1130: DtypeWarning:列(4,5,7,16)为混合类型。指定dtype 选项导入或设置low_memory=False。

为什么dtype选项与low_memory相关,为什么low_memory=False帮助?


当前回答

根据Jerald Achaibar给出的答案,我们可以检测混合Dytpes警告,并且只在警告发生时使用较慢的python引擎:

import warnings

# Force mixed datatype warning to be a python error so we can catch it and reattempt the 
# load using the slower python engine
warnings.simplefilter('error', pandas.errors.DtypeWarning)
try:
    df = pandas.read_csv(path, sep=sep, encoding=encoding)
except pandas.errors.DtypeWarning:
    df = pandas.read_csv(path, sep=sep, encoding=encoding, engine="python")

其他回答

正如fireynx前面提到的,如果显式指定了dtype,并且存在与该dtype不兼容的混合数据,则加载将崩溃。我使用了这样的转换器作为变通方法来更改数据类型不兼容的值,这样数据仍然可以加载。

def conv(val):
    if not val:
        return 0    
    try:
        return np.float64(val)
    except:        
        return np.float64(0)

df = pd.read_csv(csv_file,converters={'COL_A':conv,'COL_B':conv})

Try:

dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')

根据熊猫的文件:

dtype:列的类型名称或字典->类型

至于low_memory,默认为True,还没有文档。但我认为这无关紧要。错误消息是通用的,所以无论如何您都不需要处理low_memory。希望这对你有所帮助,如果你还有其他问题,请告诉我

我在一个~400MB的文件中遇到了类似的问题。设置low_memory=False对我有用。首先做一些简单的事情,我会检查你的数据帧是否比你的系统内存大,重新启动,在继续之前清理RAM。如果你仍然遇到错误,请确保你的.csv文件是正确的,在Excel中快速查看并确保没有明显的损坏。损坏的原始数据会造成严重破坏。

df = pd.read_csv('somefile.csv', low_memory=False)

这应该能解决问题。当从CSV中读取1.8M行时,我得到了完全相同的错误。

这对我很管用!

dashboard_df = pd.read_csv(p_file, sep=';', error_bad_lines=False, index_col=False, dtype='unicode')