人生苦短,我用 Pythonhtml
前文传送门:python
小白学 Python 数据分析(2):Pandas (一)概述github
小白学 Python 数据分析(3):Pandas (二)数据结构 Series数据结构
小白学 Python 数据分析(4):Pandas (三)数据结构 DataFramespa
小白学 Python 数据分析(5):Pandas (四)基础操做(1)查看数据excel
小白学 Python 数据分析(6):Pandas (五)基础操做(2)数据选择code
小白学 Python 数据分析(7):Pandas (六)数据导入orm
小白学 Python 数据分析(8):Pandas (七)数据预处理htm
前一篇文章咱们介绍了数据预处理中数据有问题的几种状况以及通常处理办法。
很常常,当咱们拿到数据的时候,首先须要肯定拿到的是正确类型的数据,若是数据类型不正确,通常经过数据类型的转化
你们应该都知道 Excel 中数据类型比较多,经常使用的有文本、数字、货币、时间、日期等等,在 Pandas 中,相对而言数据类型就少了不少,经常使用的有 int64 , float64 , object , datetime64 等等。
仍是使用前面的示例,咱们先看下当前数据表中的数据类型,这里使用的 dtypes
,示例以下:
import pandas as pd # 相对路径 df = pd.read_excel("result_data.xlsx") print(df) # 输出结果 plantform read_num fans_num rank_num like_num create_date 0 cnblog 215.0 0 118.0 0 2019-11-23 23:00:10 1 cnblog 215.0 0 118.0 0 2019-11-23 23:00:10 2 juejin NaN 0 -2.0 1 2019-11-23 23:00:03 3 csdn 1652.0 69 0.0 24 2019-11-23 23:00:02 4 cnblog 650.0 3 NaN 0 2019-11-22 23:00:15 .. ... ... ... ... ... ... 404 juejin 212.0 0 -1.0 2 2020-02-20 23:00:02 405 csdn 1602.0 1 0.0 1 2020-02-20 23:00:01 406 cnblog 19.0 0 41.0 0 2020-02-21 23:00:05 407 juejin 125.0 1 -4.0 0 2020-02-21 23:00:02 408 csdn 1475.0 8 0.0 3 2020-02-21 23:00:02 print(df.dtypes) # 输出结果 plantform object read_num float64 fans_num int64 rank_num float64 like_num int64 create_date datetime64[ns] dtype: object
固然,咱们若是想单独知道某一列的数据类型,也能够这么用:
import pandas as pd # 相对路径 df = pd.read_excel("result_data.xlsx") print(df['read_num'].dtypes) # 输出结果 float64
当咱们须要转换数据类型的时候,可使用 astype()
这个方法,在使用的时候讲须要转化的目标类型写在 astype()
后面括号里便可:
import pandas as pd # 相对路径 df = pd.read_excel("result_data.xlsx") print(df['fans_num'].astype('float64')) # 输出结果 0 0.0 1 0.0 2 0.0 3 69.0 4 3.0 ... 404 0.0 405 1.0 406 0.0 407 1.0 408 8.0 Name: fans_num, Length: 409, dtype: float64
有些时候,咱们拿到的数据表是没有索引的,若是没有索引, Pandas 会默认的为咱们添加从 0 开始的天然数做为行索引。而列索引会默认取第一行。好比咱们建立了一个没有表头的 Excel ,以下:
没有表头这样的数据看起来很难懂,咱们先导入到 Pandas 中看下效果:
import pandas as pd df1 = pd.read_excel("demo.xlsx") print(df1) # 输出结果 A1 1001 小红 1000 0 A2 1002 小王 2000 1 A3 1003 小明 3000 2 A4 1004 小朱 4000 3 A5 1005 小黑 5000
这时,咱们想给这个数据表加上列索引,这里可使用 columns ,以下:
import pandas as pd df1 = pd.read_excel("demo.xlsx") df1.columns = ['编号', '序号', '姓名', '消费金额'] print(df1) # 输出结果 编号 序号 姓名 消费金额 0 A2 1002 小王 2000 1 A3 1003 小明 3000 2 A4 1004 小朱 4000 3 A5 1005 小黑 5000
如今咱们有了列索引,可是若是这时我并不想用自动生成的天然数做为行索引,想替换成数据表中的序号,能够怎么作呢?
这里须要使用到的是 set_index()
这个方法,在括号中指明须要使用的列名便可:
import pandas as pd df1 = pd.read_excel("demo.xlsx") print(df1.set_index('编号')) # 输出结果 序号 姓名 消费金额 编号 A2 1002 小王 2000 A3 1003 小明 3000 A4 1004 小朱 4000 A5 1005 小黑 5000
本篇的内容就到这里结束了,今天的内容有点短,溜了溜了~~
老规矩,全部的示例代码都会上传至代码管理仓库 Github 和 Gitee 上,方便你们取用。
原文出处:https://www.cnblogs.com/babycomeon/p/12376001.html