【问题标题】:pandas read excel "General" column as object熊猫将excel“常规”列作为对象读取
【发布时间】:2015-12-04 04:47:00
【问题描述】:

我有一个看起来像这样的.xls文件

col_a       col_b   col_c   col_d
5376594                     hello
12028432                    world
17735732    hello   12      hello
17736843    world           world

当我阅读文件时

test = pandas.read_excel('F:/test.xls')

使用以下列类型读取该表:

>>> test.dtypes
col_a       int64
col_b       object
col_c       float64
col_d       object

我遇到的问题是我想为col_bcol_d 提供字符串列。由于我是python的新手,请您指点我

  1. 幕后发生了什么?和
  2. 是否有任何参数可以调整以将列读取为字符串?

编辑: 评论中要求的第一行的类型

>>> type(test.iloc[0]['col_a'])
<class 'numpy.int64'>
>>> type(test.iloc[0]['col_b'])
<class 'float'>
>>> type(test.iloc[0]['col_c'])
<class 'numpy.float64'>
>>> type(test.iloc[0]['col_d'])
<class 'str'>

【问题讨论】:

  • 它可能仍然是str type(test.iloc[0]['col_a']) 显示什么?
  • @EdChum 请查看编辑
  • col_bfloat 的原因是因为你有缺失值,NaN 值需要 float dtype 来表示它们
  • 所以基本上dtypes 是正确的并且适用于列 b 和 d 由于缺少值而混合了 dtype
  • @EdChum 谢谢。有没有办法“强制”熊猫读取为字符串?

标签: python excel pandas import


【解决方案1】:

您可以在pandas.read_csv 中定义dtype

dtype:数据类型名称或列名称到数据类型的字典。如果未指定,将推断数据类型。 (engine='python' 不支持)

以及为什么 NaN 是 float - here
dtypes 的类型是here(在页面末尾)。

测试:

import pandas
import io
import numpy

col_types = {"col_a": numpy.int32, "col_b": str, "col_c": str, "col_d": str}

temp=u"""col_a,col_b,col_c,col_d
5376594,,,hello
12028432,,,world
17735732,hello,12,hello
17736843,world,,world"""

test = pandas.read_csv(io.StringIO(temp), header=0, sep=",", dtype=col_types)



print type(test.iloc[0]['col_a'])
print type(test.iloc[0]['col_b'])
print type(test.iloc[0]['col_c'])
print type(test.iloc[0]['col_d'])
#
#<type 'numpy.int32'>
#<type 'float'>
#<type 'float'>
#<type 'str'>

print type(test.iloc[2]['col_a'])
print type(test.iloc[2]['col_b'])
print type(test.iloc[2]['col_c'])
print type(test.iloc[2]['col_d']).
#
#<type 'numpy.int32'>
#<type 'str'>
#<type 'str'>
#<type 'str'>

print test
print test.dtypes
#
#col_a     int32
#col_b    object
#col_c    object
#col_d    object
#dtype: object

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2021-11-11
    • 2016-10-16
    • 2021-05-21
    相关资源
    最近更新 更多