目录

Pandas

Pandas是基于Numpy创建的Python库,为Python提供了易于使用的数据结构和数据分析工具。

使用以下语句导入 Pandas 库:

import pandas as pd

Pandas 数据结构

Series-序列

存储任意类型数据的一维数组

 s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'])

结果输出

a    3
b   -5
c    7
d    4

DataFrame-数据框

存储不同类型数据的二维数组

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

结果输出

     Country    Capital    Population
0    Belgium    Brussels    11190846
1    India      New Delhi   1303171035
2    Brazil     Brasília    207847528

输入输出

读取/写入CSV

pd.read_csv('file.csv', nrows=5)#nrows的值代表读取多少行数据,如果读取全部的数据则不设置该参数
df.to_csv('myDataFrame.csv')

读取/写入Excel

pd.read_excel('file.xlsx')
pd.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1')

读取内含多个表的Excel

xlsx = pd.ExcelFile('file.xls')
df = pd.read_excel(xlsx, 'Sheet1')

读取和写入 SQL 查询及数据库表

from sqlalchemy import create_engine
#读取
# 在Unix/Mac
engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True) # /tmp/test.db为数据库文件的绝对路径
engine = create_engine('sqlite:///tmp/test.db', convert_unicode=True) # tmp/test.db为数据库文件的相对路径

# 在Windows
engine = create_engine('sqlite:///C:\\path\\to\\foo.db') # C:\\path\\to\\foo.db为绝对路径,需要转义
engine = create_engine(r'sqlite:///C:\path\to\foo.db') # 在Windows 中使用原始字符串

# 使用内存作为数据库容器
engine = create_engine('sqlite://')
engine = create_engine('sqlite:///:memory:')
#执行sql语句
pd.read_sql("SELECT * FROM my_table;", engine)
pd.read_sql_table('my_table', engine)
pd.read_sql_query("SELECT * FROM my_table;", engine)
#read_sql()是 read_sql_table() 与 read_sql_query()的便捷打包器
#写入
pd.to_sql('myDf', engine)

调用帮助

help(pd.Series.loc)

选择(参阅 NumPy Arrays)

取值

取序列的值

s['b']

结果输出

-5

取数据框的子集

df[1:]

结果输出

  Country    Capital    Population
1    India    New Delhi   1303171035
2    Brazil   Brasília    207847528

选取、布尔索引及设置值

按位置

按行与列的位置选择某值

1. 第一种写法,使用loc函数

df.iloc[[0],[0]]#如果选取多个值,可在[]中添加序号,例df.iloc[[0,1],[0,1]]

结果输出

   Country
0    Belgium

或者

df.iloc[0,0]

结果输出

'Belgium'

2. 第二种写法,使用loc函数

df.iat[0,0]

结果输出

'Belgium'

按标签

按行与列的名称选择某值

1. 第一种写法,使用loc函数

df.loc[[0], ['Country']]

结果输出

   Country
0    Belgium

2. 第二种写法,使用at函数

df.at[0,'Country']

结果输出

'Belgium'

按标签/位置

选择某行

df.iloc[[0],:]

结果输出

   Country    Capital    Population
0    Belgium    Brussels    11190846

选择某列

df.iloc[:,[0]]

结果输出

   Country
0    Belgium
1    India
2    Brazil

布尔索引

序列 S 中没有大于1的值

s[~(s > 1)]

结果输出

b   -5

序列 S 中小于-1或大于2的值

s[(s < -1) | (s > 2)]

结果输出

a    3
b   -5
c    7
d    4

使用筛选器调整数据框

df[df['Population']>1200000000]

结果输出

   Country    Capital    Population
1    India    New Delhi    1303171035

设置值

将序列 S 中索引为 a 的值设为6

s['a'] = 6

删除数据

按索引删除序列的值 (axis=0)

s.drop(['a', 'c'])

结果输出

b   -5
d    4

按列名删除数据框的列(axis=1)

df.drop('Country', axis=1)

结果输出

   Capital    Population
0    Brussels    11190846
1    New Delhi   1303171035
2    Brasília    207847528

排序和排名

按索引排序

df.sort_index()

结果输出

   Country    Capital    Population
0    Belgium   Brussels   11190846
1    India     New Delhi  1303171035
2    Brazil    Brasília   207847528

按某列的值排序

df.sort_values(by='Country')

结果输出

   Country    Capital    Population
0    Belgium  Brussels    11190846
2    Brazil   Brasília    207847528
1    India    New Delhi   1303171035

数据框排名

df.rank()

结果输出

   Country  Capital  Population
0    1.0      2.0       1.0
1    3.0      3.0       3.0
2    2.0      1.0       2.0

查询序列与数据框的信息

基本信息

(行,列)

df.shape

结果输出

(3, 3)

获取索引的值

df.index.values

结果输出

array([0, 1, 2], dtype=int64)

获取列名

df.columns

结果输出

Index(['Country', 'Capital', 'Population'], dtype='object')

获取数据框基本信息

df.info()

结果输出

RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype 
---  ------      --------------  ----- 
 0   Country     3 non-null      object
 1   Capital     3 non-null      object
 2   Population  3 non-null      int64 
dtypes: int64(1), object(2)
memory usage: 200.0+ bytes

非Na值的数量

df.count()

结果输出

Country       3
Capital       3
Population    3

汇总

合计

df.sum()

结果输出

Country              BelgiumIndiaBrazil
Capital       BrusselsNew DelhiBrasília
Population                   1522209409

累计

df.cumsum()

结果输出

     Country             Capital                     Population
0    Belgium             Brussels                     11190846
1    BelgiumIndia        BrusselsNew Delhi            1314361881
2    BelgiumIndiaBrazil  BrusselsNew DelhiBrasília    1522209409

最小值除以最大值

df['Population'].min()/df['Population'].max()

结果输出

0.008587396204673933

索引最小值除以索引最大值

df['Population'].idxmin()/df['Population'].idxmax()

结果输出

0.0

基础统计数据

df.describe()

结果输出

         Population
count    3.000000e+00
mean     5.074031e+08
std      6.961346e+08
min      1.119085e+07
25%      1.095192e+08
50%      2.078475e+08
75%      7.555093e+08
max      1.303171e+09

平均值

df.mean()

结果输出

Population    5.074031e+08

中位数

df.median()

结果输出

Population    207847528.0

应用函数

应用匿名函数lambda

f = lambda x: x*2

应用函数

df.apply(f)

结果输出

      Country              Capital        Population
0    BelgiumBelgium    BrusselsBrussels    22381692
1    IndiaIndia        New DelhiNew Delhi  2606342070
2    BrazilBrazil      BrasíliaBrasília    415695056

对每个单元格应用函数

df.applymap(f)

结果输出

       Country          Capital          Population
0    BelgiumBelgium    BrusselsBrussels    22381692
1    IndiaIndia        New DelhiNew Delhi  2606342070
2    BrazilBrazil      BrasíliaBrasília    415695056

数据对齐

内部数据对齐

如有不一致的索引,则使用NA值:

s3 = pd.Series([7, -2, 3], index=['a', 'c', 'd'])
s + s3

结果输出

a    13.0
b     NaN
c     5.0
d     7.0

使用 Fill 方法运算

还可以使用 Fill 方法进行内部对齐运算:

s.add(s3, fill_value=0)

结果输出

a    13.0
b    -5.0
c     5.0
d     7.0

其他

s.sub(s3, fill_value=2)
s.div(s3, fill_value=4)
s.mul(s3, fill_value=3)