原文: http://zetcode.com/python/pandas/

这是 Pandas 的入门教程。 本教程展示了如何使用 Pandas 库在 Python 中进行基本数据分析。 代码示例和数据可在作者的 Github 仓库中获得。

Pandas

Pandas 是 BSD 许可的开放源代码库,为 Python 编程语言提供了高性能,易于使用的数据结构和数据分析工具。

库的名称来自“面板数据”一词,这是对数据集的计量经济学术语,其中包括对同一个人在多个时间段内的观察。

它提供用于操纵数值表和时间序列的数据结构和操作。 主要的两种数据类型是:SeriesDataFrame

DataFrame是带有标记轴(行和列)的二维大小可变的,可能是异构的表格数据结构。 它是一个类似于电子表格的数据结构。 SeriesDataFrame的单个列。 DataFrame可以看作是Series对象的字典。

安装 Pandas

使用以下命令安装 Pandas:

  1. $ pip3 install pandas

我们使用pip3命令安装pandas模块。

  1. $ pip3 install numpy

一些示例还使用numpy

Pandas 简单的例子

以下是一个简单的 Pandas 示例。

simple.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
  4. df = pd.DataFrame(data, columns=['Name', 'Age'])
  5. print(df)

在程序中,我们创建一个简单的DataFrame并将其打印到控制台。

  1. import pandas as pd

我们导入 Pandas 库。

  1. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]

这是要在框架中显示的数据。 每个嵌套列表在表中都是一行。 请注意,有很多方法可以初始化 Pandas DataFrame

  1. df = pd.DataFrame(data, columns=['Name', 'Age'])

根据数据创建一个DataFrame。 我们用columns属性给框架列名。

  1. $ python simple.py
  2. Name Age
  3. 0 Alex 10
  4. 1 Ronald 18
  5. 2 Jane 33

这是输出。 第一列是行索引。

Pandas 改变索引

我们可以更新索引,使其不从 0 开始。

change_index.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
  4. df = pd.DataFrame(data, columns=['Name', 'Age'])
  5. df.index = df.index + 1
  6. print(df)

在示例中,我们将 1 加到索引。

  1. $ python change_index.py
  2. Name Age
  3. 1 Alex 10
  4. 2 Ronald 18
  5. 3 Jane 33

这是输出。

Pandas 标量序列

以下示例创建一系列标量值。

series_scalar.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. s = pd.Series(5, index=[0, 1, 2, 3])
  4. print(s)

我们有一列包含数字。

  1. $ python series_scalar.py
  2. 0 5
  3. 1 5
  4. 2 5
  5. 3 5
  6. dtype: int64

左列是索引。

Pandas 序列ndarray

我们可以从 numpy ndarray 创建一个系列对象。

series_numpy.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. import numpy as np
  4. data = np.array(['a', 'b', 'c', 'd'])
  5. s = pd.Series(data)
  6. print(s)

该示例从ndarray创建一列字母。

  1. $ python series_numpy.py
  2. 0 a
  3. 1 b
  4. 2 c
  5. 3 d
  6. dtype: object

这是输出。

Pandas 序列字典

可以从 Python 字典创建系列。

series_dict.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. import numpy as np
  4. data = {'coins' : 22, 'pens' : 3, 'books' : 28}
  5. s = pd.Series(data)
  6. print(s)

该示例根据一系列项目创建一个系列对象。

  1. $ python series_dict.py
  2. coins 22
  3. pens 3
  4. books 28
  5. dtype: int64

索引由项目名称组成。

Pandas 序列检索

以下示例从一系列对象中检索值。

series_retrieve.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
  4. print(s[0])
  5. print('-----------------------')
  6. print(s[1:4])
  7. print('-----------------------')
  8. print(s[['a','c','d']])

该示例从系列对象检索值。

  1. print(s[0])

在这里,我们得到一个值。

  1. print(s[1:4])

我们通过它们的索引检索行。

  1. print(s[['a','c','d']])

在这里,我们通过索引标签获取值。

  1. $ python series_retrieve.py
  2. 1
  3. -----------------------
  4. b 2
  5. c 3
  6. d 4
  7. dtype: int64
  8. -----------------------
  9. a 1
  10. c 3
  11. d 4
  12. dtype: int64

这是输出。

Pandas 自定义索引

索引列不必是数字。 我们可以创建自己的自定义索引。

custom_index.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
  4. "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
  5. "area": [8.516, 17.10, 3.286, 9.597, 1.221],
  6. "population": [200.4, 143.5, 1252, 1357, 52.98]}
  7. frame = pd.DataFrame(data)
  8. print(frame)
  9. print('------------------------------')
  10. frame.index = ["BR", "RU", "IN", "CH", "SA"]
  11. print(frame)

在示例中,我们从数据字典创建数据框架。 我们先打印数据框,然后使用index属性更改索引列。

  1. $ python custom_index.py
  2. country capital area population
  3. 0 Brazil Brasilia 8.516 200.40
  4. 1 Russia Moscow 17.100 143.50
  5. 2 India New Dehli 3.286 1252.00
  6. 3 China Beijing 9.597 1357.00
  7. 4 South Africa Pretoria 1.221 52.98
  8. ------------------------------
  9. country capital area population
  10. BR Brazil Brasilia 8.516 200.40
  11. RU Russia Moscow 17.100 143.50
  12. IN India New Dehli 3.286 1252.00
  13. CH China Beijing 9.597 1357.00
  14. SA South Africa Pretoria 1.221 52.98

这是输出。

Pandas 索引、列和值

PandasDataFrame具有三个基本部分:索引,列和值。

index_vals_cols.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
  4. df = pd.DataFrame(data, columns=['Name', 'Age'])
  5. print(f'Index: {df.index}')
  6. print(f'Columns: {df.columns}')
  7. print(f'Values: {df.values}')

该示例显示数据框的索引,列和值。

  1. $ python index_vals_cols.py
  2. Index: RangeIndex(start=0, stop=3, step=1)
  3. Columns: Index(['Name', 'Age'], dtype='object')
  4. Values: [['Alex' 10]
  5. ['Ronald' 18]
  6. ['Jane' 33]]

这是输出。

Pandas 的总和和最大值

下面的示例计算数据帧列中值的总和和最大值。 它还使用numpy库。

sum_max.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. import numpy as np
  4. df = pd.DataFrame(np.arange(0, 1200, 2), columns=['A'])
  5. # df.index = df.index + 1
  6. print(sum(df['A']))
  7. print(max(df['A']))
  8. # print(df)

该示例计算最大值和值之和。 它使用numpyarange()函数生成值数组。

  1. print(sum(df['A']))

当计算总和值时,我们通过名称来引用该列。

  1. $ sum_max.py
  2. 359400
  3. 1198

这是输出。

Pandas 读 CSV

Pandas 使用read_csv()从 CSV 文件读取数据。

military_spending.csv

  1. Pos, Country, Amount (Bn. $), GDP
  2. 1, United States, 610.0, 3.1
  3. 2, China, 228.0, 1.9
  4. 3, Saudi Arabia, 69.4, 10.0
  5. 4, Russia, 66.3, 4.3
  6. 5, India, 63.9, 2.5
  7. 6, France, 57.8, 2.3
  8. 7, United Kingdom, 47.2, 1.8
  9. 8, Japan, 45.4, 0.9
  10. 9, Germany, 44.3, 1.2
  11. 10, South Korea, 39.2, 2.6
  12. 11, Brazil, 29.3, 1.4
  13. 12, Italy Italy, 29.2, 1.5
  14. 13, Australia Australia, 27.5, 2.0
  15. 14, Canada Canada, 20.6, 1.3
  16. 15, Turkey Turkey, 18.2, 2.2

这是一个简单的 CSV 文件,其中包含有关国家军事支出的数据。

注意:CSV 文件在第一行中可能具有可选的列名。

read_from_csv.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("military_spending.csv")
  4. print(df.to_string(index=False))

该示例从military_spending.csv文件中读取所有数据,并以表格格式将其打印到控制台。 它使用read_csv()方法。

  1. print(df.to_string(index=False))

由于我们有positions列,因此我们从输出中隐藏索引。

  1. $ python read_from_csv.py
  2. Pos Country Amount (Bn. $) GDP
  3. 1 United States 610.0 3.1
  4. 2 China 228.0 1.9
  5. 3 Saudi Arabia 69.4 10.0
  6. 4 Russia 66.3 4.3
  7. 5 India 63.9 2.5
  8. 6 France 57.8 2.3
  9. 7 United Kingdom 47.2 1.8
  10. 8 Japan 45.4 0.9
  11. 9 Germany 44.3 1.2
  12. 10 South Korea 39.2 2.6
  13. 11 Brazil 29.3 1.4
  14. 12 Italy Italy 29.2 1.5
  15. 13 Australia Australia 27.5 2.0
  16. 14 Canada Canada 20.6 1.3
  17. 15 Turkey Turkey 18.2 2.2

这是输出。

Pandas 写 CSV

to_csv()DataFrame写入 CSV 文件。

write_csv.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
  4. df = pd.DataFrame(data, columns=['Name', 'Age'])
  5. df.to_csv("users.csv", index=False)

该示例将数据写入users.csv文件。

Pandas 随机行

可以使用sample()选择数据帧中的随机行。

random_sample.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("military_spending.csv")
  4. print(df.sample(3))

在该示例中,我们从数据框中打印了三个随机行。

Pandas 数据定位

to_dict()将数据框转换为 Python 字典。 字典可以显示在不同的数据输出中。

data_orient.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
  4. df = pd.DataFrame(data, columns=['Name', 'Age'])
  5. print('list')
  6. print(df.to_dict(orient='list'))
  7. print('************************************')
  8. print('series')
  9. print(df.to_dict(orient='series'))
  10. print('************************************')
  11. print('dict')
  12. print(df.to_dict(orient='dict'))
  13. print('************************************')
  14. print('split')
  15. print(df.to_dict(orient='split'))
  16. print('************************************')
  17. print('records')
  18. print(df.to_dict(orient='records'))
  19. print('************************************')
  20. print('index')
  21. print(df.to_dict(orient='index'))

该示例以六种不同格式将数据帧打印到控制台。

Pandas 描述

describe()方法生成描述性统计数据,该数据统计总结了NaN值之外的数据集分布的集中趋势,离散度和形状。

describing.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. s1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])
  4. s2 = pd.Series([12, 23, 31, 14, 11, 61, 17, 18])
  5. data = {'Vals 1': s1, 'Vals 2': s2}
  6. df = pd.DataFrame(data)
  7. print(df.describe())

该示例从数据框中打印描述性统计信息。

  1. $ python describe.py
  2. Vals 1 Vals 2
  3. count 8.00000 8.000000
  4. mean 4.50000 23.375000
  5. std 2.44949 16.535136
  6. min 1.00000 11.000000
  7. 25% 2.75000 13.500000
  8. 50% 4.50000 17.500000
  9. 75% 6.25000 25.000000
  10. max 8.00000 61.000000

这是输出。

Pandas 计数

下一个示例对值进行计数。 您可以在 Github 仓库中找到employees.csv文件。

counting.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("employees.csv")
  4. print(df.count())
  5. print(f'Number of columns: {len(df.columns)}')
  6. print(df.shape)

count()方法计算每列的值数。 用len(df.columns)检索列数。 shape返回表示数据帧维数的元组。

  1. $ python counting.py
  2. First Name 933
  3. Gender 855
  4. Start Date 1000
  5. Last Login Time 1000
  6. Salary 1000
  7. Bonus % 1000
  8. Senior Management 933
  9. Team 957
  10. dtype: int64
  11. Number of columns: 8
  12. (1000, 8)

请注意,这些列具有不同数量的值,因为缺少某些值。

Pandas head()tail()

使用head()tail()方法,我们可以显示数据帧的前 n 行和后 n 行。

head_tail.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("military_spending.csv")
  4. print(df.head(4))
  5. print('*******************************************')
  6. print(df.tail(4))

该示例显示数据框的前四行和后四行。

  1. $ python head_tail.py
  2. Pos Country Amount (Bn. $) GDP
  3. 0 1 United States 610.0 3.1
  4. 1 2 China 228.0 1.9
  5. 2 3 Saudi Arabia 69.4 10.0
  6. 3 4 Russia 66.3 4.3
  7. *******************************************
  8. Pos Country Amount (Bn. $) GDP
  9. 11 12 Italy Italy 29.2 1.5
  10. 12 13 Australia Australia 27.5 2.0
  11. 13 14 Canada Canada 20.6 1.3
  12. 14 15 Turkey Turkey 18.2 2.2

这是输出。

Pandas 没有标题和索引

当我们显示数据框时,我们可以隐藏标题和索引。

no_header_index.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("military_spending.csv")
  4. print(df.head(4).to_string(header=False, index=False))

通过将headerindex属性设置为False,我们将输出没有标题和索引的数据帧。

  1. $ python no_header.py
  2. 1 United States 610.0 3.1
  3. 2 China 228.0 1.9
  4. 3 Saudi Arabia 69.4 10.0
  5. 4 Russia 66.3 4.3

这是输出。 (值 1 到 4 来自pos列。)

Pandas loc()

loc()方法允许按标签或布尔数组访问一组行和列。

select_loc.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = {'Items': ['coins', 'pens', 'books'], 'Quantity': [22, 28, 3]}
  4. df = pd.DataFrame(data, index=['A', 'B', 'C'])
  5. print(df.loc['A'])
  6. print('-------------------------------')
  7. print(df.loc[['A', 'B'], ['Items']])

该示例使用loc()函数。

  1. print(df.loc['A'])

在这里,我们得到第一行。 我们通过其索引标签访问该行。

  1. print(df.loc[['A', 'B'], ['Items']])

在这里,我们获得了Items列的前两行。

  1. $ python select_loc.py
  2. Items coins
  3. Quantity 22
  4. Name: A, dtype: object
  5. -------------------------------
  6. Items
  7. A coins
  8. B pens

这是输出。

第二个示例显示如何通过布尔数组选择。

select_loc2.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. data = {'Items': ['coins', 'pens', 'books'], 'Quantity': [22, 28, 3]}
  4. df = pd.DataFrame(data, index=['A', 'B', 'C'])
  5. print(df.loc[[True, False, True], ['Items', 'Quantity']])

该示例通过布尔数组选择行。

  1. $ select_loc2.py
  2. Items Quantity
  3. A coins 22
  4. C books 3

这是输出。

在第三个示例中,我们在选择时应用条件。

select_loc3.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("employees.csv")
  4. data = df.loc[(df['Salary'] > 10000) & (df['Salary'] < 50000)]
  5. print(data.head(5))

该示例从employees.csv文件中打印出符合条件的前五行:薪水在 10000 至 50000 之间。

Pandas iloc

iloc函数允许基于整数位置的索引,以按位置进行选择。

select_iloc.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. df = pd.read_csv("employees.csv")
  4. # integer-location based indexing for selection by position.
  5. # Multiple row and column selections using iloc and DataFrame
  6. print(df.iloc[0:6]) # first six rows of dataframe
  7. print('--------------------------------------')
  8. print(df.iloc[:, 0:2]) # first two columns of data frame with all rows
  9. print('--------------------------------------')
  10. # 1st, 4th, 7th, 25th row + 1st 6th 8th column
  11. print(df.iloc[[0, 3, 6, 24], [0, 5, 7]])
  12. print('--------------------------------------')
  13. # first 5 rows and 5th, 6th, 7th columns of data frame
  14. print(df.iloc[:5, 5:8])
  15. print('--------------------------------------')

该示例显示了如何使用iloc()选择行和列的各种组合。

Pandas 排序

sort_values()按升序或降序对系列进行排序。

sorting.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. s1 = pd.Series([2, 1, 4, 5, 3, 8, 7, 6])
  4. s2 = pd.Series([12, 23, 31, 14, 11, 61, 17, 18])
  5. data = {'Col 1': s1, 'Col 2': s2}
  6. df = pd.DataFrame(data)
  7. print(df.sort_values('Col 1', ascending=True))
  8. print('------------------------------------')
  9. print('Sorted')
  10. print(df.sort_values('Col 2', ascending=False))

该示例按升序或降序对列进行排序。

  1. $ python sorting.py
  2. Col 1 Col 2
  3. 1 1 23
  4. 0 2 12
  5. 4 3 11
  6. 2 4 31
  7. 3 5 14
  8. 7 6 18
  9. 6 7 17
  10. 5 8 61
  11. ------------------------------------
  12. Sorted
  13. Col 1 Col 2
  14. 5 8 61
  15. 2 4 31
  16. 1 1 23
  17. 7 6 18
  18. 6 7 17
  19. 3 5 14
  20. 0 2 12
  21. 4 3 11

这是输出。

在下一个示例中,我们按多列排序。

sorting2.py

  1. #!/usr/bin/env python3
  2. import pandas as pd
  3. s1 = pd.Series([1, 2, 1, 2, 2, 1, 2, 2])
  4. s2 = pd.Series(['A', 'A', 'B', 'A', 'C', 'C', 'C', 'B'])
  5. data = {'Col 1': s1, 'Col 2': s2}
  6. df = pd.DataFrame(data)
  7. print(df.sort_values(['Col 1', 'Col 2'], ascending=[True, False]))

该示例按包含整数的第一列进行排序。 然后,将考虑第一排序的结果对第二列进行排序。

  1. $ python sorting2.py
  2. Col 1 Col 2
  3. 5 1 C
  4. 2 1 B
  5. 0 1 A
  6. 4 2 C
  7. 6 2 C
  8. 7 2 B
  9. 1 2 A
  10. 3 2 A

这是输出。

在本教程中,我们使用了 Pandas 库。

您可能也对以下相关教程感兴趣: Python 教程OpenPyXL 教程Python Requests 教程Python CSV 教程, 或列出所有 Python 教程