Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 使用多级列时忽略数据类型_Pandas_Csv_Dataframe_Header - Fatal编程技术网

Pandas 使用多级列时忽略数据类型

Pandas 使用多级列时忽略数据类型,pandas,csv,dataframe,header,Pandas,Csv,Dataframe,Header,将DataFrame.read\u csv与多级列一起使用时(使用标题读取=),Panda似乎忽略了dtype=关键字。 有没有办法让熊猫使用传递的类型? 我正在从CSV读取大数据集,因此尝试以正确的格式读取数据,以节省CPU和内存 我尝试使用带有元组和字符串的数据类型传递dict。似乎dtype需要字符串。至少我观察到,如果我传递级别0键,类型将被分配,但不幸的是,这意味着具有相同级别0标签的所有列将获得相同的类型。在下面的esample中,列(A,int16)和(A,int32)将获得类型对

将DataFrame.read\u csv与多级列一起使用时(使用
标题读取=
),Panda似乎忽略了
dtype=
关键字。 有没有办法让熊猫使用传递的类型? 我正在从CSV读取大数据集,因此尝试以正确的格式读取数据,以节省CPU和内存

我尝试使用带有元组和字符串的数据类型传递dict。似乎dtype需要字符串。至少我观察到,如果我传递级别0键,类型将被分配,但不幸的是,这意味着具有相同级别0标签的所有列将获得相同的类型。在下面的esample中,列(A,int16)和(A,int32)将获得类型对象,(B,float32)和(B,int16)将获得float32

将熊猫作为pd导入
df=pd.DataFrame({
('A','int16'):pd.系列([1,2,3,4],dtype='int16'),
('A','int32'):pd.系列([132,232,332,432],dtype='int32'),
('B','float32'):pd.系列([1.01,1.02,1.03,1.04],dtype='float32'),
('B','int16'):pd.Series([21,22,23,24],dtype='int16'))
打印(df)
df.to_csv('test_df.csv'))
打印(df.dtypes)
#带有级别0/1标签的完整列名元组无效
df_new=pd.read_csv(
“test_df.csv”,
标题=列表(范围(2)),
数据类型={
('A','int16'):'int16',
('A','int32'):'int32'
})
打印(df_新的.d类型)
#对dtype=使用0级标签似乎有效
df_new2=pd.read_csv(
“test_df.csv”,
标题=列表(范围(2)),
数据类型={
“A”:“object”,
“B”:“浮动32”
})
打印(df_new2.dtypes)
我希望第二个
print(df.dtypes)
输出与第一个
print(df.dtypes)
相同的列类型,但它似乎根本没有使用
dtype=
参数,并推断出导致内存密集型的类型

我错过什么了吗

提前谢谢你的留言

import pandas as pd
    df=  pd.DataFrame({
        ('A', 'int16'):   pd.Series([1, 2, 3, 4], dtype='int16'),
        ('A', 'int32'):   pd.Series([132, 232, 332, 432], dtype='int32'), 
        ('B', 'float32'): pd.Series([1.01, 1.02, 1.03, 1.04], dtype='float32'),
        ('B', 'int16'):   pd.Series([21, 22, 23, 24], dtype='int16')})
    print(df)
    df.to_csv('test_df.csv')
    print(df.dtypes)
    <i># full column name tuples with level 0/1 labels don't work</i>
    df_new= pd.read_csv(
        'test_df.csv',
        header=list(range(2)),
        dtype = {
            ('A', 'int16'): 'int16', 
            ('A', 'int32'): 'int32'
        })
    print(df_new.dtypes)
    <i># using the level 0 labels for dtype= seems to work</i>
    df_new2= pd.read_csv(
        'test_df.csv', 
        header=list(range(2)), 
        dtype={
            'A':'object', 
            'B': 'float32'
        })
    print(df_new2.dtypes)