pandas阅读excel“常规”栏作为对象
我有一个.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')
该表使用以下列types进行读取:
>>> test.dtypes col_a int64 col_b object col_c float64 col_d object
我有的问题是,我想有col_b
和col_d
string列。 由于我在python上是个新手,请你指点一下
- 幕后发生了什么? 和
- 有没有任何参数来调整阅读列作为string?
编辑:在评论中问的第一行的types
>>> 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'>
你可以在pandas.read_csv中定义dtype 。
dtype :数据types名称或列名字典到数据types。 如果未指定,则会推断数据types。 (不支持engine ='python')
为什么NaN是float
– 在这里 。
dtypes的types在这里 (在页面的末尾)。
testing:
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