保存pandas Dataframe 为32位浮点数

zfycwa2u  于 6个月前  发布在  其他
关注(0)|答案(4)|浏览(46)

我在pandas中有一些数据,我试图保存为32位浮点数,但我总是得到64位浮点数。我最好的尝试是这样的:

df['store'] = pd.DataFrame(data).astype(float32)

字符串
但它不工作..任何想法?

wqnecbli

wqnecbli1#

使用numpy.float32

In [320]:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a':np.random.randn(10)})
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 0 to 9
Data columns (total 1 columns):
a    10 non-null float64
dtypes: float64(1)
memory usage: 160.0 bytes

In [323]:   
df['a'].astype(np.float32)

Out[323]:
0    0.966618
1   -0.331942
2    0.906349
3   -0.089582
4   -0.722004
5    0.668103
6    0.230314
7   -1.707631
8    1.806862
9    1.783765
Name: a, dtype: float32

字符串
您可以看到dtype现在是float32

50few1ms

50few1ms2#

现在有一个比公认的答案更简单的解决方案,不需要导入numpy:

.astype('float32')

字符串
示例如下:

df['store'] = pd.DataFrame(data).astype('float32') 

df['rating'] = (df['rating']/2).astype('float32')

brtdzjyr

brtdzjyr3#

注意,如果内存有限或者你想要更多的空间,你可以选择df['a'].astype(np.float32)作为答案,或者同样地用np.float16np.float64代替数字,np.int16np.int32np.int64代替整数,如果您的应用程序的准确性很好,您可以将许多应用程序降低到int16/float16并缩小数据占用空间。

8cdiaqws

8cdiaqws4#

我不得不将所有数值列转换为32位,并且单独进行转换是不可扩展的。

# Creating an example DF
int_values = [1, 2, 3, 4, 5]
text_values = ["alpha", "beta", "gamma", "delta", "epsilon"]
float_values = [0.0, 0.25, 0.5, 0.75, 1.0]
df = pd.DataFrame({
    "int_col": int_values,
    "text_col": text_values,
    "float_col": float_values
})

print(df)
   int_col text_col  float_col
0        1    alpha       0.00
1        2     beta       0.25
2        3    gamma       0.50
3        4    delta       0.75
4        5  epsilon       1.00

个字符
您可以通过pd.info()检查原始df和转换后的df2

print(df.info(), df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   int_col    5 non-null      int64    <--
 1   text_col   5 non-null      object 
 2   float_col  5 non-null      float64  <--
dtypes: float64(1), int64(1), object(1)
memory usage: 248.0+ bytes
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   int_col    5 non-null      float32  <--
 1   text_col   5 non-null      object 
 2   float_col  5 non-null      float32  <--
dtypes: float32(2), object(1)
memory usage: 208.0+ bytes
None None

相关问题