熊猫-使用read_csv

时间:2019-04-12 07:57:06

标签: python pandas import dask large-data

我正在尝试加载几个相当大的CSV(总计:大约3000万行/ 7GB)。有些列是intsfloats混合的-我希望这些列为np.float16


理想地,将使用dtype的{​​{1}}参数来使整个导入过程更有效。但是,这些混合数据列会引发错误。

这是代码,以及相应的错误:

read_csv
def import_processing(filepath, cols, null_cols):
    result = pd.read_csv(filepath, header = None, names = cols.keys(), dtype = cols)
    result.drop(null_cols, axis = 1, inplace = True)
    return result

data_cols = { 'feature_0' : np.float32,
              'feature_1' : np.float32,
              'feature_2' : np.uint32,
              'feature_3' : np.uint64,
              'feature_4' : np.uint64,
              'feature_5' : np.float16,
              'feature_6' : np.float16,
              'feature_7' : np.float16,
              'feature_8' : np.float16,
              'feature_9' : np.float16,
              'feature_10' : np.float16,
              'feature_11' : np.float16,
              'feature_12' : np.float16,
              'feature_13' : np.float16,
              'feature_14' : np.float16,
              'feature_15' : np.float16,
              'feature_16' : np.float16,
              'feature_17' : np.float16,
              'feature_18' : np.float16,
              'feature_19' : np.float16,
              'feature_20' : np.float16,
              'feature_21' : np.float16,
              'feature_22' : np.float16,
              'feature_23' : np.float16,
              'feature_24' : np.float16,
              'feature_25' : 'M8[ns]',
              'feature_26' : 'M8[ns]',
              'feature_27' : np.uint64,
              'feature_28' : np.uint32,
              'feature_29' : np.uint64,
              'feature_30' : np.uint32}

files = ['./file_0.csv', './file_1.csv', './file_2.csv']
all_data = [import_processing(f, data_cols, ['feature_0', 'feature_1']) for f in files]


但是,如果我不使用TypeError: Cannot cast array from dtype('O') to dtype('float16') according to the rule 'safe' 参数,则由于所有混合数据类型列都以dtype而不是dtype('O')的形式导入,因此导入速度会大大降低。 / p>

我一直在通过首先应用np.float16(不确定为什么不会抛出相同的错误)来解决此问题,该方法将所有列都转换为pd.to_numeric,然后使用{{1 }}转换,以将每一列转换成我想要的类型(包括到np.float64的那些混合数据类型列)。

这个过程很慢,所以我想知道是否有更好的方法。目前,我的(非常慢的)工作功能如下:

astype()

编辑:我已经读到,利用Dask(通常)是在Python中管理大型数据集的一种更为有效的方法。我以前从未使用过它,据我所知,它基本上使用对Pandas的调用来处理许多操作-所以我想它会遇到相同的数据类型问题。

1 个答案:

答案 0 :(得分:0)

从错误中我猜测是您的一列不是严格数字,并且您的数据中有一些文本,因此Pandas将其解释为object-dtype列。无法强制此数据为float16类型。但这只是一个猜测。