因为
注意,并不是原始csv文件中的所有列都具有浮动类型。我只需要将float32设置为浮动列的默认设置。
发布于 2015-05-28 00:17:08
尝试:
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 64’,然后使用字典理解来创建一个字典,其中这些列作为键,'np.float32‘作为每个键的值。
最后,它使用'c‘引擎(向列分配dtype所必需的)读取整个文件,然后将float32_cols字典作为参数传递给dtype。
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)发布于 2020-11-26 12:52:12
这里有一种解决方案,它不依赖于.join,也不需要读取文件两次:
float64_cols = df.select_dtypes(include='float64').columns
mapper = {col_name: np.float32 for col_name in float64_cols}
df = df.astype(mapper)或者踢得像一条直线:
df = df.astype({c: np.float32 for c in df.select_dtypes(include='float64').columns})发布于 2019-10-22 15:40:20
@Alexander's是一个很好的答案。有些列可能需要精确。如果是这样,您可能需要在列表理解中添加更多条件,以排除any或all内置的一些列的方便性:
float_cols = [c for c in df_test if all([df_test[c].dtype == "float64",
not df_test[c].name == 'Latitude', not df_test[c].name =='Longitude'])] https://stackoverflow.com/questions/30494569
复制相似问题