根据 pandas 中的列索引在csv文件导入期间定义数据类型 [英] Defining Data Type during csv file import based on column index in pandas

查看:43
本文介绍了根据 pandas 中的列索引在csv文件导入期间定义数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要导入一个包含300多个列的csv文件,在这些列中,仅第一列需要指定为类别,而其余列的浮点数应为32或更少.我猜想我可以通过列索引指定列的数据类型.我的问题是:基于列索引指定数据类型的最佳方法是什么?

I need to import a csv file that has 300+ columns, among these columns, only the first column needs to specified as a category, while the rest of the columns should be float 32 or less. I am guessing that I could specify columns' data types via column indexes. My question is: What is an optimal way to specify data types based on column indexes?

Col_A   Col_B   Col_C   Col_D
001       1       2      1.2
002       2       3      3.5
003       3       4.5      7
004       4       6.5     10

我尝试的代码是:

df = pd.read_csv(path, low_memory=False,  
             dtype={'Col_A': 'category', [2:]: np.float32)}

推荐答案

读取两次,第一次获取所有列,第二次读取时指定dtype.

read it twice, first time get all the columns, second time, specify dtype when reading.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.to_csv('tmp.csv',index=False)

path = 'tmp.csv'
df =pd.read_csv(path)
type_dict = {}

for key in df.columns:
    if key == 'A':
        type_dict[key]='category'
    else:
        type_dict[key]=np.float32
df = pd.read_csv(path,dtype=type_dict)
print(df.dtypes)

这篇关于根据 pandas 中的列索引在csv文件导入期间定义数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆