gpt4 book ai didi

python - 如何强制 pandas read_csv 对所有浮点列使用 float32?

转载 作者:太空狗 更新时间:2023-10-29 20:21:27 25 4
gpt4 key购买 nike

因为

  • 我不需要 double
  • 我的机器内存有限,我想处理更大的数据集
  • 我需要将提取的数据(作为矩阵)传递给 BLAS 库,单精度的 BLAS 调用比 double 等效调用快 2 倍。

请注意,并非原始 csv 文件中的所有列都具有浮点类型。我只需要将 float32 设置为浮点列的默认值。

最佳答案

尝试:

import numpy as np
import pandas as pd

# Sample 100 rows of data to determine dtypes.
df_test = pd.read_csv(filename, nrows=100)

float_cols = [c for c in df_test if df_test[c].dtype == "float64"]
float32_cols = {c: np.float32 for c in float_cols}

df = pd.read_csv(filename, engine='c', dtype=float32_cols)

这里先读取100行数据的样本(按需修改),判断每一列的类型。

它创建了一个包含“float64”列的列表,然后使用字典推导式创建一个字典,将这些列作为键,将“np.float32”作为每个键的值。

最后,它使用“c”引擎(将数据类型分配给列所必需)读取整个文件,然后将 float32_cols 字典作为参数传递给数据类型。

df = pd.read_csv(filename, nrows=100)
>>> df
int_col float1 string_col float2
0 1 1.2 a 2.2
1 2 1.3 b 3.3
2 3 1.4 c 4.4

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 4 columns):
int_col 3 non-null int64
float1 3 non-null float64
string_col 3 non-null object
float2 3 non-null float64
dtypes: float64(2), int64(1), object(1)

df32 = pd.read_csv(filename, engine='c', dtype={c: np.float32 for c in float_cols})
>>> df32.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 4 columns):
int_col 3 non-null int64
float1 3 non-null float32
string_col 3 non-null object
float2 3 non-null float32
dtypes: float32(2), int64(1), object(1)

关于python - 如何强制 pandas read_csv 对所有浮点列使用 float32?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com