PythonPandas教程展示了如何使用Pandaslibrary在Python中进行基本数据分析。代码示例和数据可在作者的Github存储库中找到。
熊猫
Pandas是一个开源的BSD许可库,为Python编程语言提供高性能、易于使用的数据结构和数据分析工具。
库的名称来自术语“面板数据”,这是一个计量经济学术语,指的是包含同一个人在多个时间段内的观察结果的数据集。
它提供了用于处理数字表和时间序列的数据结构和操作。主要的两种数据类型是:Series
和DataFrame
。
DataFrame
是一种二维大小可变的、具有标记轴(行和列)的潜在异构表格数据结构。它是一种类似于电子表格的数据结构。Series
是DataFrame
的单列。DataFrame
可以被认为是Series
对象的字典。
PythonPandas安装
使用以下命令安装Pandas:
$ pip3 install pandas
我们使用pip3
命令安装pandas
模块。
$ pip3 install numpy
一些示例还使用了numpy
。
熊猫简单示例
以下是一个简单的Pandas示例。
#!/usr/bin/python import pandas as pd data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(df)
在程序中,我们创建了一个简单的DataFrame
并将其打印到控制台。
import pandas as pd
我们导入Pandas库。
data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
这是要在框架中显示的数据。每个嵌套列表都是表中的一行。请注意,有很多方法可以初始化PandasDataFrame
。
df = pd.DataFrame(data, columns=['Name', 'Age'])
DataFrame
是从数据创建的。我们用columns
属性给框架列名。
$ python simple.py Name Age 0 Alex 10 1 Ronald 18 2 Jane 33
这是输出。第一列是行索引。
Pandas变化指数
我们可以更新索引,使其不从0开始。
#!/usr/bin/python import pandas as pd data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]] df = pd.DataFrame(data, columns=['Name', 'Age']) df.index = df.index + 1 print(df)
在示例中,我们将索引加1。
$ python change_index.py Name Age 1 Alex 10 2 Ronald 18 3 Jane 33
Pandas标量级数
以下示例创建了一系列标量值。
#!/usr/bin/python import pandas as pd s = pd.Series(5, index=[0, 1, 2, 3]) print(s)
我们有一列包含五。
$ python series_scalar.py 0 5 1 5 2 5 3 5 dtype: int64
左边一列是索引。
熊猫系列赛
我们可以从numpyndarray
创建一个系列对象。
#!/usr/bin/python import pandas as pd import numpy as np data = np.array(['a', 'b', 'c', 'd']) s = pd.Series(data) print(s)
该示例从ndarray
创建一列字母。
$ python series_numpy.py 0 a 1 b 2 c 3 d dtype: object
熊猫系列字典
可以从Python字典创建系列。
#!/usr/bin/python import pandas as pd import numpy as np data = {'coins' : 22, 'pens' : 3, 'books' : 28} s = pd.Series(data) print(s)
该示例根据项目字典创建一个系列对象。
$ python series_dict.py coins 22 pens 3 books 28 dtype: int64
索引由项目名称组成。
Pandas系列检索
以下示例从系列对象中检索值。
#!/usr/bin/python import pandas as pd s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e']) print(s[0]) print('-----------------------') print(s[1:4]) print('-----------------------') print(s[['a','c','d']])
该示例从系列对象中检索值。
print(s[0])
这里我们得到一个值。
print(s[1:4])
我们通过索引检索行。
print(s[['a','c','d']])
这里我们通过索引标签获取值。
$ python series_retrieve.py 1 ----------------------- b 2 c 3 d 4 dtype: int64 ----------------------- a 1 c 3 d 4 dtype: int64
Pandas自定义索引
索引列不必是数字。我们可以创建自己的自定义索引。
#!/usr/bin/python import pandas as pd data = {"country": ["Brazil", "Russia", "India", "China", "South Africa"], "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"], "area": [8.516, 17.10, 3.286, 9.597, 1.221], "population": [200.4, 143.5, 1252, 1357, 52.98]} frame = pd.DataFrame(data) print(frame) print('------------------------------') frame.index = ["BR", "RU", "IN", "CH", "SA"] print(frame)
在示例中,我们从数据字典中创建了一个数据框。我们打印了数据框,然后使用index
属性更改了索引列。
$ python custom_index.py country capital area population 0 Brazil Brasilia 8.516 200.40 1 Russia Moscow 17.100 143.50 2 India New Dehli 3.286 1252.00 3 China Beijing 9.597 1357.00 4 South Africa Pretoria 1.221 52.98 ------------------------------ country capital area population BR Brazil Brasilia 8.516 200.40 RU Russia Moscow 17.100 143.50 IN India New Dehli 3.286 1252.00 CH China Beijing 9.597 1357.00 SA South Africa Pretoria 1.221 52.98
Pandas索引、列和值
PandasDataFrame
具有三个基本部分:索引、列和值。
#!/usr/bin/python import pandas as pd data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(f'Index: {df.index}') print(f'Columns: {df.columns}') print(f'Values: {df.values}')
该示例打印数据框的索引、列和值。
$ python index_vals_cols.py Index: RangeIndex(start=0, stop=3, step=1) Columns: Index(['Name', 'Age'], dtype='object') Values: [['Alex' 10] ['Ronald' 18] ['Jane' 33]]
Pandas求和和最大值
以下示例计算数据框列中的总和和最大值。它还使用numpy
库。
#!/usr/bin/python import pandas as pd import numpy as np df = pd.DataFrame(np.arange(0, 1200, 2), columns=['A']) # df.index = df.index + 1 print(sum(df['A'])) print(max(df['A'])) # print(df)
该示例计算最大值和值的总和。它使用numpy的
arange
函数生成一个值数组。
print(sum(df['A']))
当我们计算总和值时,我们通过名称引用该列。
$ sum_max.py 359400 1198
Pandas读取CSV
Pandas使用read_csv
从CSV文件中读取数据。
Pos, Country, Amount (Bn. $), GDP 1, United States, 610.0, 3.1 2, China, 228.0, 1.9 3, Saudi Arabia, 69.4, 10.0 4, Russia, 66.3, 4.3 5, India, 63.9, 2.5 6, France, 57.8, 2.3 7, United Kingdom, 47.2, 1.8 8, Japan, 45.4, 0.9 9, Germany, 44.3, 1.2 10, South Korea, 39.2, 2.6 11, Brazil, 29.3, 1.4 12, Italy Italy, 29.2, 1.5 13, Australia Australia, 27.5, 2.0 14, Canada Canada, 20.6, 1.3 15, Turkey Turkey, 18.2, 2.2
这是一个简单的CSV文件,其中包含有关各国军费开支的数据。
#!/usr/bin/python import pandas as pd df = pd.read_csv("military_spending.csv") print(df.to_string(index=False))
该示例从military_spending.csv
文件中读取所有数据,并以表格格式将其打印到控制台。它使用read_csv
方法。
print(df.to_string(index=False))
因为我们有位置列,所以我们在输出中隐藏了索引。
$ python read_from_csv.py Pos Country Amount (Bn. $) GDP 1 United States 610.0 3.1 2 China 228.0 1.9 3 Saudi Arabia 69.4 10.0 4 Russia 66.3 4.3 5 India 63.9 2.5 6 France 57.8 2.3 7 United Kingdom 47.2 1.8 8 Japan 45.4 0.9 9 Germany 44.3 1.2 10 South Korea 39.2 2.6 11 Brazil 29.3 1.4 12 Italy Italy 29.2 1.5 13 Australia Australia 27.5 2.0 14 Canada Canada 20.6 1.3 15 Turkey Turkey 18.2 2.2
熊猫写CSV
DataFrame
使用to_csv
写入CSV文件。
#!/usr/bin/python import pandas as pd data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]] df = pd.DataFrame(data, columns=['Name', 'Age']) df.to_csv("users.csv", index=False)
该示例将数据写入users.csv
文件。
熊猫随机行
可以使用sample
选择数据框中的随机行。
#!/usr/bin/python import pandas as pd df = pd.read_csv("military_spending.csv") print(df.sample(3))
在示例中,我们从数据框中打印三个随机行。
Pandas数据导向
to_dict
将数据框转换为Python字典。字典可以显示在不同的数据输出中。
#!/usr/bin/python import pandas as pd data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]] df = pd.DataFrame(data, columns=['Name', 'Age']) print('list') print(df.to_dict(orient='list')) print('************************************') print('series') print(df.to_dict(orient='series')) print('************************************') print('dict') print(df.to_dict(orient='dict')) print('************************************') print('split') print(df.to_dict(orient='split')) print('************************************') print('records') print(df.to_dict(orient='records')) print('************************************') print('index') print(df.to_dict(orient='index'))
该示例以六种不同的格式将数据框打印到控制台。
熊猫描述
describe
方法生成描述性统计数据,总结数据集分布的集中趋势、离散度和形状,不包括NaN
值。
#!/usr/bin/python import pandas as pd s1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8]) s2 = pd.Series([12, 23, 31, 14, 11, 61, 17, 18]) data = {'Vals 1': s1, 'Vals 2': s2} df = pd.DataFrame(data) print(df.describe())
该示例从数据框中打印描述性统计信息。
$ python describe.py Vals 1 Vals 2 count 8.00000 8.000000 mean 4.50000 23.375000 std 2.44949 16.535136 min 1.00000 11.000000 25% 2.75000 13.500000 50% 4.50000 17.500000 75% 6.25000 25.000000 max 8.00000 61.000000
熊猫数数
下一个示例对值进行计数。您可以在Github存储库中找到employees.csv
文件。
#!/usr/bin/python import pandas as pd df = pd.read_csv("employees.csv") print(df.count()) print(f'Number of columns: {len(df.columns)}') print(df.shape)
count
方法计算每列值的数量。使用len(df.columns)
检索列数。shape
返回表示数据框维度的元组。
$ python counting.py First Name 933 Gender 855 Start Date 1000 Last Login Time 1000 Salary 1000 Bonus % 1000 Senior Management 933 Team 957 dtype: int64 Number of columns: 8 (1000, 8)
请注意,这些列具有不同数量的值,因为缺少一些值。
熊猫的头和尾
使用head
和tail
方法,我们可以显示数据框中的第一行和最后n行。
#!/usr/bin/python import pandas as pd df = pd.read_csv("military_spending.csv") print(df.head(4)) print('*******************************************') print(df.tail(4))
该示例显示数据框中的第一行和最后四行。
$ python head_tail.py Pos Country Amount (Bn. $) GDP 0 1 United States 610.0 3.1 1 2 China 228.0 1.9 2 3 Saudi Arabia 69.4 10.0 3 4 Russia 66.3 4.3 ******************************************* Pos Country Amount (Bn. $) GDP 11 12 Italy Italy 29.2 1.5 12 13 Australia Australia 27.5 2.0 13 14 Canada Canada 20.6 1.3 14 15 Turkey Turkey 18.2 2.2
Pandas没有标题和索引
我们可以在显示数据框时隐藏表头和索引。
#!/usr/bin/python import pandas as pd df = pd.read_csv("military_spending.csv") print(df.head(4).to_string(header=False, index=False))
通过设置header
和index
属性为False
,我们输出没有header和index的数据帧。
$ python no_header.py 1 United States 610.0 3.1 2 China 228.0 1.9 3 Saudi Arabia 69.4 10.0 4 Russia 66.3 4.3
这是输出。(值1到4来自pos列。)
熊猫位置
loc
方法允许通过标签或布尔数组访问一组行和列。
#!/usr/bin/python import pandas as pd data = {'Items': ['coins', 'pens', 'books'], 'Quantity': [22, 28, 3]} df = pd.DataFrame(data, index=['A', 'B', 'C']) print(df.loc['A']) print('-------------------------------') print(df.loc[['A', 'B'], ['Items']])
该示例使用loc
函数。
print(df.loc['A'])
这里我们得到第一行。我们通过其索引标签访问该行。
print(df.loc[['A', 'B'], ['Items']])
这里我们得到Items列的前两行。
$ python select_loc.py Items coins Quantity 22 Name: A, dtype: object ------------------------------- Items A coins B pens
第二个示例展示了如何通过布尔数组进行选择。
#!/usr/bin/python import pandas as pd data = {'Items': ['coins', 'pens', 'books'], 'Quantity': [22, 28, 3]} df = pd.DataFrame(data, index=['A', 'B', 'C']) print(df.loc[[True, False, True], ['Items', 'Quantity']])
该示例通过布尔数组选择行。
$ select_loc2.py Items Quantity A coins 22 C books 3
在第三个示例中,我们在选择时应用条件。
#!/usr/bin/python import pandas as pd df = pd.read_csv("employees.csv") data = df.loc[(df['Salary'] > 10000) & (df['Salary'] < 50000)] print(data.head(5))
该示例打印employees.csv
文件中符合条件的前五行:薪水在10000到50000之间。
大熊猫iloc
iloc
函数允许基于整数位置的索引,以便按位置进行选择。
#!/usr/bin/python import pandas as pd df = pd.read_csv("employees.csv") # integer-location based indexing for selection by position. # Multiple row and column selections using iloc and DataFrame print(df.iloc[0:6]) # first six rows of dataframe print('--------------------------------------') print(df.iloc[:, 0:2]) # first two columns of data frame with all rows print('--------------------------------------') # 1st, 4th, 7th, 25th row + 1st 6th 8th column print(df.iloc[[0, 3, 6, 24], [0, 5, 7]]) print('--------------------------------------') # first 5 rows and 5th, 6th, 7th columns of data frame print(df.iloc[:5, 5:8]) print('--------------------------------------')
该示例展示了如何使用iloc
选择行和列的各种组合。
熊猫排序
sort_values
按升序或降序对序列进行排序。
#!/usr/bin/python import pandas as pd s1 = pd.Series([2, 1, 4, 5, 3, 8, 7, 6]) s2 = pd.Series([12, 23, 31, 14, 11, 61, 17, 18]) data = {'Col 1': s1, 'Col 2': s2} df = pd.DataFrame(data) print(df.sort_values('Col 1', ascending=True)) print('------------------------------------') print('Sorted') print(df.sort_values('Col 2', ascending=False))
该示例按升序或降序对列进行排序。
$ python sorting.py Col 1 Col 2 1 1 23 0 2 12 4 3 11 2 4 31 3 5 14 7 6 18 6 7 17 5 8 61 ------------------------------------ Sorted Col 1 Col 2 5 8 61 2 4 31 1 1 23 7 6 18 6 7 17 3 5 14 0 2 12 4 3 11
在下一个示例中,我们按多列排序。
#!/usr/bin/python import pandas as pd s1 = pd.Series([1, 2, 1, 2, 2, 1, 2, 2]) s2 = pd.Series(['A', 'A', 'B', 'A', 'C', 'C', 'C', 'B']) data = {'Col 1': s1, 'Col 2': s2} df = pd.DataFrame(data) print(df.sort_values(['Col 1', 'Col 2'], ascending=[True, False]))
该示例按包含整数的第一列进行排序。然后第二列根据第一次排序的结果进行排序。
$ python sorting2.py Col 1 Col 2 5 1 C 2 1 B 0 1 A 4 2 C 6 2 C 7 2 B 1 2 A 3 2 A
在本教程中,我们使用了Pandas库。
列出所有Python教程。