Pandas 语法总结

Pandas 语法总结

介绍

Pandas 是基于 NumPy 的一种数据处理工具,该工具为了解决数据分析任务而创建。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的函数和方法。

Pandas 的数据结构:Pandas 主要有 Series(一维数组),DataFrame(二维数组),Panel(三维数组),Panel4D(四维数组),PanelND(更多维数组)等数据结构。其中 Series 和 DataFrame 应用的最为广泛。
– Series 是一维带标签的数组,它可以包含任何数据类型。包括整数,字符串,浮点数,Python 对象等。Series 可以通过标签来定位。
– DataFrame 是二维的带标签的数据结构。==我们可以通过标签来定位数据。这是 NumPy 所没有的。==

知识点

本次实验涉及的知识点主要有:
– 创建Series
– Series基本操作
– 创建DataFrame
– DataFrame基本操作
– DataFrame文件操作
– Series,DataFrame和多索引
– 透视表
– 数据清洗
– 数据预处理
– 可视化

基础部分

1.导入 Pandas 模块

1. 导入 Pandas

输入:

import pandas as pd

2.查看 Pandas 版本信息

输入:

print(pd.__version__)

2.创建 Series 数据类型

==Pandas 中,Series 可以被看作由 1 列数据组成的数据集。==

创建 Series 语法:s = pd.Series(data, index=index),可以通过多种方式进行创建,以下介绍了 3 个常用方法。

2.1 从列表创建 Series

输入:

arr = [0, 1, 2, 3, 4]
s1 = pd.Series(arr)  # 如果不指定索引,则默认从 0 开始
s1

提示:前面的 0,1,2,3,4 为当前 Series 的索引,后面的 0,1,2,3,4 为 Series 的值。

2.2 从 Ndarray 创建 Series

输入:

import numpy as np
n = np.random.randn(5)  # 创建一个随机 Ndarray 数组

index = ['a', 'b', 'c', 'd', 'e']
s2 = pd.Series(n, index=index)
s2

输出:

a   -1.617725
b   -0.059218
c   -1.610177
d    0.408564
e   -1.513803
dtype: float64

2.3 从字典创建 Series

输入:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
s3 = pd.Series(d)
s3

输出:

a    1
b    2
c    3
d    4
e    5
dtype: int64

3.Series 基本操作

3.1 修改 Series 索引

输入:

print(s1)  # 以 s1 为例

s1.index = ['A', 'B', 'C', 'D', 'E']  # 修改后的索引
s1

输出:

0    0
1    1
2    2
3    3
4    4
dtype: int64

A    0
B    1
C    2
D    3
E    4
dtype: int64

3.2 Series 纵向拼接

输入:

s4 = s3.append(s1)  # 将 s1 拼接到 s3
s4

输出:

a    1
b    2
c    3
d    4
e    5
A    0
B    1
C    2
D    3
E    4
dtype: int64

3.3 Series 按指定索引删除元素

输入:

print(s4)
s4 = s4.drop('e')  # 删除索引为 e 的值
s4

输出:

a    1
b    2
c    3
d    4
A    0
B    1
C    2
D    3
E    4
dtype: int64

3.4 Series 按指定索引查找元素

输入:

s4['B']

输出:

1

3.5 Series 切片操作

输入:

s4[:3]

输出:

a    1
b    2
c    3
dtype: int64

4. Series 运算

4.1 Series 加法运算

Series 的加法运算是按照索引计算,如果索引不同则填充为 NaN(空值)。

输入:

s4.add(s3)

输出:

A    NaN
B    NaN
C    NaN
D    NaN
E    NaN
a    2.0
b    4.0
c    6.0
d    8.0
e    NaN
dtype: float64

4.2 Series 减法运算

Series的减法运算是按照索引对应计算,如果不同则填充为 NaN(空值)。

输入:

s4.sub(s3)

输出:

A    NaN
B    NaN
C    NaN
D    NaN
E    NaN
a    0.0
b    0.0
c    0.0
d    0.0
e    NaN
dtype: float64

4.3 Series 乘法运算

Series 的乘法运算是按照索引对应计算,如果索引不同则填充为 NaN(空值)。

输入:

s4.mul(s3)

输出:

A     NaN
B     NaN
C     NaN
D     NaN
E     NaN
a     1.0
b     4.0
c     9.0
d    16.0
e     NaN
dtype: float64

4.4 Series 除法运算

Series 的除法运算是按照索引对应计算,如果索引不同则填充为 NaN(空值)。

输入:

s4.div(s3)

输出:

A    NaN
B    NaN
C    NaN
D    NaN
E    NaN
a    1.0
b    1.0
c    1.0
d    1.0
e    NaN
dtype: float64

4.5 Series 求中位数

输入:

s4.median()

输出:

2.0

4.6 Series 求和

输入:

s4.sum()

输出:

20

4.7 Series 求最小值

输入:

s4.min()

输出:

0

5.创建 DataFrame 数据类型

与 Sereis 不同,DataFrame 可以存在多列数据。一般情况下,DataFrame 也更加常用。

5.1 通过 NumPy 数组创建 DataFrame

输入:

dates = pd.date_range('today', periods=6)  # 定义时间序列作为 index
num_arr = np.random.randn(6, 4)  # 传入 numpy 随机数组
columns = ['A', 'B', 'C', 'D']  # 将列表作为列名
df1 = pd.DataFrame(num_arr, index=dates, columns=columns)
df1

输出:

                                A           B           C           D
2018-12-18 02:39:40.519323  -0.551914   -1.277574   0.789487    0.153490
2018-12-19 02:39:40.519323  2.344228    -1.323991   -0.124677   0.296460
2018-12-20 02:39:40.519323  0.979317    0.434025    -0.060349   -1.838303
2018-12-21 02:39:40.519323  -0.200960   -1.610445   0.603207    -1.518570
2018-12-22 02:39:40.519323  -0.955526   -1.444734   -0.729784   -0.708490
2018-12-23 02:39:40.519323  0.746531    0.619194    -0.856048   -1.421594

5.2 通过字典数组创建 DataFrame

输入:

data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
        'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
        'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df2 = pd.DataFrame(data, index=labels)
df2

输出:

    animal  age visits  priority
a   cat      2.5    1   yes
b   cat      3.0    3   yes
c   snake    0.5    2   no
d   dog      NaN    3   yes
e   dog      5.0    2   no
f   cat      2.0    3   no
g   snake    4.5    1   no
h   cat      NaN    1   yes
i   dog      7.0    2   no
j   dog      3.0    1   no

5.3 查看 DataFrame 的数据类型

输入:

df2.dtypes

输出:

animal       object
age         float64
visits        int64
priority     object
dtype: object

6.DataFrame 基本操作

6.1 预览 DataFrame 的前 5 行数据

此方法对快速了解陌生数据集结构十分有用。

输入:

df2.head()   # 默认为显示 5 行,可根据需要在括号中填入希望预览的行数

输出:

   animal   age   visits    priority
a   cat      2.5    1          yes
b   cat     3.0     3          yes
c   snake   0.5     2           no
d   dog     NaN     3          yes
e   dog     5.0     2           no

6.2 查看 DataFrame 的后 3 行数据

输入:

df2.tail(3)

输出:

   animal   age visits  priority
h   cat     NaN     1   yes
i   dog     7.0     2   no
j   dog     3.0     1   no

6.3 查看DataFrame 的索引

输入:

df2.index

输出:

Index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], dtype='object')

6.4 查看 DataFrame 的列名

输入:

df2.columns

输出:

Index(['animal', 'age', 'visits', 'priority'], dtype='object')

6.5 查看 DataFrame 的数值

输入:

df2.values

输出:

array([['cat', 2.5, 1, 'yes'],
       ['cat', 3.0, 3, 'yes'],
       ['snake', 0.5, 2, 'no'],
       ['dog', nan, 3, 'yes'],
       ['dog', 5.0, 2, 'no'],
       ['cat', 2.0, 3, 'no'],
       ['snake', 4.5, 1, 'no'],
       ['cat', nan, 1, 'yes'],
       ['dog', 7.0, 2, 'no'],
       ['dog', 3.0, 1, 'no']], dtype=object)

6.6 查看 DataFrame 的统计数据

输入:

df2.describe()

输出:

             age    visits
count   8.000000    10.000000
mean    3.437500    1.900000
std 2.007797    0.875595
min 0.500000    1.000000
25% 2.375000    1.000000
50% 3.000000    2.000000
75% 4.625000    2.750000
max 7.000000    3.000000

6.7 DataFrame 转置操作

输入:

df2.T

输出:

         a     b    c   d   e   f   g   h   i   j
animal  cat cat snake   dog dog cat snake   cat dog dog
age 2.5 3   0.5 NaN 5   2   4.5 NaN 7   3
visits  1   3   2   3   2   3   1   1   2   1
priority    yes yes no  yes no  no  no  yes no  no

6.8 对 DataFrame 进行按列排序

输入:

df2.sort_values(by='age')  # 按 age 升序排列

输出:

   animal   age visits  priority
c   snake   0.5 2   no
f   cat 2.0 3   no
a   cat 2.5 1   yes
b   cat 3.0 3   yes
j   dog 3.0 1   no
g   snake   4.5 1   no
e   dog 5.0 2   no
i   dog 7.0 2   no
d   dog NaN 3   yes
h   cat NaN 1   yes

6.9 对 DataFrame 数据切片

输入:

df2[1:3]

输出:

    animal  age visits  priority
b    cat    3.0 3   yes
c    snake  0.5 2   no

6.10 对 DataFrame 通过标签查询(单列)

输入:

df2['age']

输出:

a    2.5
b    3.0
c    0.5
d    NaN
e    5.0
f    2.0
g    4.5
h    NaN
i    7.0
j    3.0
Name: age, dtype: float64

或:
输入:

df2.age  # 等价于 df2['age']

输出:

a    2.5
b    3.0
c    0.5
d    NaN
e    5.0
f    2.0
g    4.5
h    NaN
i    7.0
j    3.0
Name: age, dtype: float64

6.11 对 DataFrame 通过标签查询(多列)

输入:

df2[['age', 'animal']]  # 传入一个列名组成的列表

输出:

    age animal
a   2.5 cat
b   3.0 cat
c   0.5 snake
d   NaN dog
e   5.0 dog
f   2.0 cat
g   4.5 snake
h   NaN cat
i   7.0 dog
j   3.0 dog

6.12 对 DataFrame 通过位置查询

输入:

df2.iloc[1:3]  # 查询 2,3 行

输出:

    animal  age visits  priority
b   cat      3.0    3   yes
c   snake    0.5    2   no

6.13 DataFrame 副本拷贝

输入:

# 生成 DataFrame 副本,方便数据集被多个不同流程使用
df3 = df2.copy()
df3

输出:

    animal  age visits  priority
a   cat 2.5 1   yes
b   cat 3.0 3   yes
c   snake   0.5 2   no
d   dog NaN 3   yes
e   dog 5.0 2   no
f   cat 2.0 3   no
g   snake   4.5 1   no
h   cat NaN 1   yes
i   dog 7.0 2   no
j   dog 3.0 1   no

6.14 判断 DataFrame 元素是否为空

输入:

df3.isnull()  # 如果为空则返回为 True

输出:

    animal  age visits  priority
a   False   False   False   False
b   False   False   False   False
c   False   False   False   False
d   False   True    False   False
e   False   False   False   False
f   False   False   False   False
g   False   False   False   False
h   False   True    False   False
i   False   False   False   False
j   False   False   False   False

6.15 添加列数据

输入:

num = pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], index=df3.index)

df3['No.'] = num  # 添加以 'No.' 为列名的新数据列
df3

输出:


animal age visits priority No. a cat 2.5 1 yes 0 b cat 3.0 3 yes 1 c snake 0.5 2 no 2 d dog NaN 3 yes 3 e dog 5.0 2 no 4 f cat 2.0 3 no 5 g snake 4.5 1 no 6 h cat NaN 1 yes 7 i dog 7.0 2 no 8 j dog 3.0 1 no 9

6.16 根据 DataFrame 的下标值进行更改

输入:

# 修改第 2 行与第 1 列对应的值 3.0 → 2.0
df3.iat[1, 0] = 2  # 索引序号从 0 开始,这里为 1, 0
df3

输出:


animal age visits priority No. a cat 2.5 1 yes 0 b 2 3.0 3 yes 1 c snake 0.5 2 no 2 d dog NaN 3 yes 3 e dog 5.0 2 no 4 f cat 2.0 3 no 5 g snake 4.5 1 no 6 h cat NaN 1 yes 7 i dog 7.0 2 no 8 j dog 3.0 1 no 9

6.17 根据 DataFrame 的标签对数据进行修改

输入:

df3.loc['f', 'age'] = 1.5
df3

输出:

   animal   age visits  priority
a   cat 2.5 1   yes
b   cat 3.0 3   yes
c   snake   0.5 2   no
d   dog NaN 3   yes
e   dog 5.0 2   no
f   cat 1.5 3   no
g   snake   4.5 1   no
h   cat NaN 1   yes
i   dog 7.0 2   no
j   dog 3.0 1   no

6.18 DataFrame 求平均值操作

输入:

df3.mean()

输出:

age       3.375
visits    1.900
dtype: float64

6.19 对 DataFrame 中任意列做求和操作

输入:

df3['visits'].sum()

输出:

19

7.字符串操作

7.1 将字符串转化为小写字母

输入:

string = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca',
                    np.nan, 'CABA', 'dog', 'cat'])
print(string)
string.str.lower()

输出:

0       A
1       B
2       C
3    Aaba
4    Baca
5     NaN
6    CABA
7    dog 
8     cat

dtype: object
0       a
1       b
2       c
3    aaba
4    baca
5     NaN
6    caba
7    dog 
8     cat
dtype: object

7.2 将字符串转化为大写字母

输入:

string.str.upper()

输出:

0       A
1       B
2       C
3    AABA
4    BACA
5     NaN
6    CABA
7    DOG 
8     CAT
dtype: object

8. DataFrame 缺失值操作

8.1 对缺失值进行填充

输入:

df4 = df3.copy()
print(df4)
df4.fillna(value=3)

输出:

   animal  age  visits priority
a    cat  2.5       1      yes
b    cat  3.0       3      yes
c  snake  0.5       2       no
d    dog  NaN       3      yes
e    dog  5.0       2       no
f    cat  1.5       3       no
g  snake  4.5       1       no
h    cat  NaN       1      yes
i    dog  7.0       2       no
j    dog  3.0       1       no

  animal    age visits  priority
a   cat 2.5 1   yes
b   cat 3.0 3   yes
c   snake   0.5 2   no
d   dog 3.0 3   yes
e   dog 5.0 2   no
f   cat 1.5 3   no
g   snake   4.5 1   no
h   cat 3.0 1   yes
i   dog 7.0 2   no
j   dog 3.0 1   no

8.2 删除存在缺失值的行

输入:

df5 = df3.copy()
print(df5)
df5.dropna(how='any')  # 任何存在 NaN 的行都将被删除

输出:

   animal  age  visits priority
a    cat  2.5       1      yes
b    cat  3.0       3      yes
c  snake  0.5       2       no
d    dog  NaN       3      yes
e    dog  5.0       2       no
f    cat  1.5       3       no
g  snake  4.5       1       no
h    cat  NaN       1      yes
i    dog  7.0       2       no
j    dog  3.0       1       no

  animal    age visits  priority
a   cat 2.5 1   yes
b   cat 3.0 3   yes
c   snake   0.5 2   no
e   dog 5.0 2   no
f   cat 1.5 3   no
g   snake   4.5 1   no
i   dog 7.0 2   no
j   dog 3.0 1   no

8.3 DataFrame 按指定列对齐

输入:

left = pd.DataFrame({'key': ['foo1', 'foo2'], 'one': [1, 2]})
right = pd.DataFrame({'key': ['foo2', 'foo3'], 'two': [4, 5]})

print(left)
print(right)

# 按照 key 列对齐连接,只存在 foo2 相同,所以最后变成一行
pd.merge(left, right, on='key')

输出:

 key  one
0  foo1    1
1  foo2    2

 key  two
0  foo2    4
1  foo3    5

 key    one two
0   foo2    2   4

9.DataFrame 文件操作

9.1 CSV 文件写入

输入:

df3.to_csv('animal.csv')
print("写入成功.")

输出:

写入成功.

9.2 CSV 文件读取

输入:

df_animal = pd.read_csv('animal.csv')
df_animal

输出:

    Unnamed: 0  animal  age visits  priority
0   a   cat 2.5 1   yes
1   b   cat 3.0 3   yes
2   c   snake   0.5 2   no
3   d   dog NaN 3   yes
4   e   dog 5.0 2   no
5   f   cat 1.5 3   no
6   g   snake   4.5 1   no
7   h   cat NaN 1   yes
8   i   dog 7.0 2   no
9   j   dog 3.0 1   no

9.3 Excel 写入操作

输入:

df3.to_excel('animal.xlsx', sheet_name='Sheet1')
print("写入成功.")

输出:

写入成功.

9.4 Excel 读取操作

输入:

pd.read_excel('animal.xlsx', 'Sheet1', index_col=None, na_values=['NA'])

输出:

    animal  age visits  priority
a   cat 2.5 1   yes
b   cat 3.0 3   yes
c   snake   0.5 2   no
d   dog NaN 3   yes
e   dog 5.0 2   no
f   cat 1.5 3   no
g   snake   4.5 1   no
h   cat NaN 1   yes
i   dog 7.0 2   no
j   dog 3.0 1   no
赞赏
Nemo版权所有丨如未注明,均为原创丨本网站采用BY-NC-SA协议进行授权,转载请注明转自:https://nemo.cool/42.html

Nemo

文章作者

推荐文章

发表回复

textsms
account_circle
email

Pandas 语法总结
介绍 Pandas 是基于 NumPy 的一种数据处理工具,该工具为了解决数据分析任务而创建。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的函数和方法。 Pandas …
扫描二维码继续阅读
2019-05-08