Skip to main content
 首页 » 编程设计

python之使用 to_csv 时如何保留数据帧的数据类型

2025年05月04日13itcoder

为了降低内存成本,我使用 astype() 指定了我的 pandas 数据框的数据类型,例如:

df['A'] = df['A'].astype(int8) 

然后我使用 to_csv() 来存储它,但是当我使用 read_csv() 再次读取它并检查 dtypes 时,我发现它仍然存储在 int64 中。 如何在将数据类型保存在本地存储中的同时保留数据类型?

请您参考如下方法:

这是一个方法:

import pandas as pd 
 
# Create Example data with types 
df = pd.DataFrame({ 
    'words': ['foo', 'bar', 'spam', 'eggs'], 
    'nums': [1, 2, 3, 4] 
}).astype(dtype={ 
    'words': 'object', 
    'nums': 'int8' 
}) 
 
def to_csv(df, path): 
    # Prepend dtypes to the top of df (from https://stackoverflow.com/a/43408736/7607701) 
    df.loc[-1] = df.dtypes 
    df.index = df.index + 1 
    df.sort_index(inplace=True) 
    # Then save it to a csv 
    df.to_csv(path, index=False) 
 
def read_csv(path): 
    # Read types first line of csv 
    dtypes = pd.read_csv('tmp.csv', nrows=1).iloc[0].to_dict() 
    # Read the rest of the lines with the types from above 
    return pd.read_csv('tmp.csv', dtype=dtypes, skiprows=[1]) 
 
 
print('Before: \n{}\n'.format(df.dtypes)) 
 
to_csv(df, 'tmp.csv') 
df = read_csv('tmp.csv') 
 
print('After: \n{}\n'.format(df.dtypes)) 

输出:

Before:  
nums       int8 
words    object 
dtype: object 
 
After:  
nums       int8 # still int8 
words    object 
dtype: object