十分钟入门pandas

教你十分钟学会使用pandas。
pandas是python数据分析的一个最重要的工具。

基本使用

# 一般以pd作为pandas的缩写
import pandas as pd

# 读取文件
df = pd.read_csv('file.csv')

# 返回数据的大小
df.shape

# 显示数据的一些对象信息和内存使用
df.info()

# 显示数据的统计量信息
df.describe()

花式索引

我们的主要数据结构就是DataFrame了,DataFrame有两部分构成,一个是列(columns)。列是有名称的或者说有标签的。另一个是索引(index),这里我们为了避孕歧义称之为行(rows)。
如图所示:


data = {'Country': ['Belgium', 'India', 'Brazil'], 'Capital': ['Brussels', 'New Delhi', 'Brasília'], 'Population': [11190846, 1303171035, 207847528]}
df = pd.DataFrame(data, columns=['Country', 'Capital', 'Population'])
>>> df
   Country    Capital  Population
0  Belgium   Brussels    11190846
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528

原始索引

原始索引就是类list的索引方式。
当索引对象是切片时就是行索引。

>>> df[1:3]
  Country    Capital  Population
1   India  New Delhi  1303171035
2  Brazil   Brasília   207847528

当索引对象是list时就是列索引。

>>> df[['Country', 'Capital']]
   Country    Capital
0  Belgium   Brussels
1    India  New Delhi
2   Brazil   Brasília

跟上面等效,上面是用了列名称,这里用了列序号。

>>> df[[0,1]]
   Country    Capital
0  Belgium   Brussels
1    India  New Delhi
2   Brazil   Brasília

位置索引

>>> df.iloc[0:2, 0:2]
   Country    Capital
0  Belgium   Brussels
1    India  New Delhi

标签索引

lociloc有两点区别:1. 列索引要用label不能用序号,2.loc的行索引左右都是闭区间。

>>> df.loc[0:2, ['Country']]
   Country
0  Belgium
1    India
2   Brazil

混合索引

其实就是位置索引和标签索引的混合使用方式。

>>> df.ix[0:2, [1,2]]
     Capital  Population
0   Brussels    11190846
1  New Delhi  1303171035
2   Brasília   207847528

条件索引

>>> df[df['Population']>1200000000]
  Country    Capital  Population
1   India  New Delhi  1303171035

数据清洗

# 如果人口没有数据用0填充
df['Population'].fillna(0, inplace=True)

速查表

练习

老样子,来写点习题吧。
100道pandas练习题
pandas练习库

参考

官方版十分钟入门pandas
pandas cookbook

猜你喜欢

转载自www.cnblogs.com/nevermoes/p/pandas.html