数据分析库pandas入门 10——数据类型转换、pandas 绘图

Pandas库使用入门10——数据类型转换、pandas 绘图

在前面关于 pandas 的文章中,笔者分别介绍了:

本篇是 Pandas 系列最后一篇,主要是补充介绍 Pandas 的数据类型转换方法和 Pandas 绘图。对原始数据集进行类型转换是经常发生的,前面文章中也都有所涉及,这里单独拿出来再总结一下。关于数据可视化(即绘图),已经有非常成熟的工具库可用,比如:matplotlib、seaborn等等,但 Pandas 也有绘图功能,这里概要介绍其最常用的绘图方法,matplotlib、seaborn绘图等留待后续梳理总结。

Pandas 数据类型转换

在 Pandas 中对数据对象进行类型转换常用的是 astype 方法和 apply 方法,前者是直接转换,后者应用其他转换函数进行转换。还有把数据列或行转换成列表或数组的 to_list 方法、 to_numpy 方法。用两个库函数:to_numericto_datetime 可以分别转换成数值型和 datetime 类型。
另外,可以使用 Series.str 将 Series 的值当作字符串处理,通过 Series.str.func 来应用各种字符串处理函数,比如 func 可以是 len、count、find、lower、split等等等等。用这种方法可以跳过 NaN 缺失值进行处理。
上述中,在 “日期时间数据类型与处理方法” 这一篇已经介绍了 to_datetime 函数和使用 astype 方法的例子;在 “几个重要的方法/函数:apply/applymap/map、cut/qcut、melt、get_dummies” 这一篇已经介绍了 apply/applymap/map 函数。除此之外,其他方法函数定义如下:

  • Series/DataFrame.astype(dtype, copy=True, errors='raise')
  • Series.to_list()
  • Series/DataFrame.to_numpy(dtype, copy=False, na_value)
  • pandas.to_numeric(arg, errors='raise', downcast)

示例如下:

import numpy as np
import pandas as pd

df = pd.DataFrame(data = [('1', '20120927', 5.0, 33, 'M', 78.5),
('2', '20120909', 5.4, 24, 'M',  np.nan),
('3', '20120815', 5.2, 23, 'F', 66.5),
('4', '20121103', 4.9, np.nan, 'M', 80),
('5', '20121122', 5.7, 54, 'F', np.nan),
('', '20120607', 5.2, 23, 'F', 66.5),
('7', '20120816', 5.3, 42, 'M', 69)],
columns=['id','date','height','age','gender','score'])
df.info()                         # 查看 df 各列类型
df['age'].astype('Int64')         # 将 'age' 列转换成 Int64 类型,缺失值 np.nan 被转换成 NAType
df['date'].astype('datetime64')   # 将 'date' 列转换成 datetime64 类型
pd.to_datetime(df['date'])        # 同上
df.astype({'date': 'datetime64',  # 将要转换类型的列以字典形式传入 astype 方法
           # 'id': 'int32',       # 'id' 列存在空串,因此用astype方法会报错
           'height': 'int64'})    # 将 'height' 列转换成 int64 类型
df['gender'].to_list()            # 将 'gender' 列转换成列表
df['score'].to_numpy(na_value=0)  # 将 'score' 列转换成 numpy 数组,缺失值用0填充
pd.to_numeric(df['id'])  # 将字符串型 'id' 列转换成数值型,空值处为 NaN,转换后该列类型为 float64,
                         # 如果该列没有 '' 空值,则转换后类型为 int64

def trans(x):
	try:
		return int(x)
	except:
		return 'NaN'
		
df['score'].apply(func=trans)  # 将 'score' 列转换成 int 类型,缺失值转换成 'NaN' 字符串

df['id'].str.len()             # 获取 'id' 列各值的串长
df['gender'].str.lower()       # 将 'gender' 列转换成小写
df['date'].str.split('2012')   # 将 'date' 列进行分割生成列表
df['date'].str.count('0')      # 统计 'data' 列中 '0' 的数量
df['gender'].str.find('M')     # 找到 'gender' 列中 'M' 并返回位置下标,若无则返回-1

Pandas 绘图

Pandas 在 matplotlib 绘图软件包的基础上单独封装了一个 plot() 接口,通过调用该接口可以实现常用的绘图操作,Series 和 DataFrame 对象的 plot 方法定义分别如下。另外,也可以用 DataFrame/Series.plot.graph 的形式,graph 或者 plot 方法中的 kind 参数可以是: line(折线图)、bar/barh(柱状图)、kde(核密度估计图)、area(区域图)、pie(饼图)、hist(直方图)、scatter(散点图)、box(箱型图)等等。

  • Series.plot(kind='line', ax, figsize, use_index=True, title, grid, legend=False, style, logx=False, logy=False,loglog=False,xticks,yticks, xlim, ylim, rot, fontsize, colormap, table=False, yerr, xerr, label, secondary_y=False, **kwds)

  • DataFrame.plot(x, y, kind='line', ax, subplots=False, sharex, sharey=False, layout, figsize, use_index=True, title, grid, legend=True, style, logx=False, logy=False, loglog=False, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table=False, yerr, xerr, secondary_y=False, sort_columns=False, **kwds)

示例如下(接续上述代码):

import matplotlib.pyplot as plt

s1 = pd.Series(np.random.randn(200), index=[str(i) for i in range(200)])
s2 = pd.Series([11,13,15,6,4,2], index=[str(i) for i in range(6)])
s1.plot(kind='line')  # 折线图,若无参数,则默认绘制折线图
plt.show()            # 显示绘制的图(后续代码进行了省略)
s2.plot(kind='bar')   # 柱状图,等效于 s2.plot.bar()
s1.plot(kind='kde')   # 核概率密度估计图,等效于 s1.plot.kde()
s2.plot(kind='area')  # 区域图
s2.plot(kind='pie')   # 饼图
s1.plot(kind='hist')  # 直方图
df.plot(kind='scatter',x='date',y='height')  # 散点图
df[['age','score']].plot(kind='box')         # 箱型图

以上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值