为了更好地掌握数据科学必备库Pandas的基本使用,本文通过精灵宝可梦的数据集实战,我们一起过一遍Pandas的基本操作,文中的代码都附有注释,并给出了结果的配图,这里是下篇,上篇链接戳这里

 

我们紧接上回操作,继续来对Pandas的基本操作进行梳理。

 

十分钟掌握Pandas基本操作(下)_Pandas

 

  • 数据切分

df1=df.loc[:399,:]
df2=df.loc[400:,:]
# 按行标签切分
df3=df.iloc[:,:6]
df4=df.iloc[:,6:]
# 按列位置切分
  • 数据合并

# 按照切片的不同维度将数据合并,下面三行代码都能获得原数据
df_new=df1.append(df2)
df_new1=pd.concat([df1,df2],axis=0)
df_new2=pd.concat([df3,df4],axis=1)

十分钟掌握Pandas基本操作(下)_Pandas_02

  • 分组

# 把宝可梦按Generation分组
df.groupby(['Generation']).count()
# 统计每一代的数目
df.groupby(['Generation']).mean()
# 查看每一代的数据均值

十分钟掌握Pandas基本操作(下)_Pandas_03

# 把宝可梦按Generation分组,并统计Speed的和以及均值
df.groupby('Generation')['Speed'].agg([np.sum,np.mean])

十分钟掌握Pandas基本操作(下)_Pandas_04

# 按多个属性分组并统计数目
df.groupby(['Generation','Type1','Legendary']).count()
# 把宝可梦按Legendary分组,并选择Legendary为真的组
df.groupby(['Legendary']).get_group(True)
  • apply

# 通过匿名函数将所有数据HP值增加1
df['HP']=df['HP'].apply(lambda x:x+1)
  • 图片绘制(默认为折线,可以选择柱状图、密度图等)

df['Attack'][:10].plot(color='red')
df['Defense'][:10].plot(color='blue')

十分钟掌握Pandas基本操作(下)_Pandas_05

  • 绘制箱线图

# 箱线图可以用于离群点的观察测
df.boxplot()

十分钟掌握Pandas基本操作(下)_Pandas_06

  • One-Hot编码

# 把Type1这一列改成One-Hot编码
# 如果某行数据Type1为Bug,那么在Type1_Bug列下为1,在其余列均为0
dummy_df=pd.get_dummies(df['Type1'],prefix='Type1')

十分钟掌握Pandas基本操作(下)_Pandas_07

  • 参考资料

Pandas官方文档

 

对于Pandas的基本操作我们就总结到这里,这个数据集还可以用来做机器学习,把宝可梦的类型作为标签来预测,或是把是否是神兽作为标签来做二分类等等,我们下回见。

 

——END——