Pandas read_excel()函数 thousands参数的使用

Pandas read_excel()函数 thousands参数的使用

最近在学习使用pandas的read_excel()函数使用,在查看API文档时,看到thousands参数的描述:

thousands [str, default None] Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.

参数说明:

传递的类型为str,默认为None。

作用: 处理Excel表中以字符串类型存储的数字,且带有类似‘,’分隔符,例如: 200,000,000, 将此类字符串转换为数值类型。

举例如下:

例如我们有这样一组数据val列是以字符串形式存储的:

date val
2014/3/1 200,000,000
2014/6/1 200,001
2014/9/1 200,002
2014/12/1 200,003
2015/3/1 200,004
2015/6/1 200,005
2015/9/1 200,006
2015/12/1 200,007
2016/3/1 200,008
2016/6/1 200,009
2016/9/1 200,010
2016/12/1 200,011
2017/3/1 200,012
2017/6/1 200,013
2017/9/1 200,014

 

我们先将该表数据使用read_excel函数读取出来,再查看val列的数据类型:

In [198]: import pandas as pd
     ...: df = pd.read_excel("records.xlsx")
     ...: df
     ...:
Out[198]:
         date          val
0    2014/3/1  200,000,000
1    2014/6/1      200,001
2    2014/9/1      200,002
3   2014/12/1      200,003
4    2015/3/1      200,004
5    2015/6/1      200,005
6    2015/9/1      200,006
7   2015/12/1      200,007
8    2016/3/1      200,008
9    2016/6/1      200,009
10   2016/9/1      200,010
11  2016/12/1      200,011
12   2017/3/1      200,012
13   2017/6/1      200,013
14   2017/9/1      200,014

In [199]: type(df['val'][0])
Out[199]: str

验证发现是str类型,但我们实际想要的是int类型,此时就可以通过thousands参数来处理。代码如下:

In [200]: import pandas as pd
     ...: df = pd.read_excel("records.xlsx", thousands=",")
     ...: df
     ...:
Out[200]:
         date        val
0    2014/3/1  200000000
1    2014/6/1     200001
2    2014/9/1     200002
3   2014/12/1     200003
4    2015/3/1     200004
5    2015/6/1     200005
6    2015/9/1     200006
7   2015/12/1     200007
8    2016/3/1     200008
9    2016/6/1     200009
10   2016/9/1     200010
11  2016/12/1     200011
12   2017/3/1     200012
13   2017/6/1     200013
14   2017/9/1     200014

In [201]: type(df['val'][0])
Out[201]: numpy.int64

这样就得到了我们想要的整型数据。

【总结】

thousandsc参数实际上是用来处理以“千分位分隔符”表示的数据的,且存储时必须为string类型。
 

 

你可能感兴趣的:(Pandas)