Python Pandas教程

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

Pandas

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

该库的名称来自术语“panel data”,这是一个计量经济学术语,指的是包括对同一个人在多个时间段的观察结果的数据集。

它提供了操作数字表和时间序列的数据结构和操作。主要的两种数据类型是:序列(Series )和数据框架(DataFrame)。

DataFrame是一个二维大小可变的、可能异构的表格数据结构,具有标记轴(行row和列column)。它是一个类似电子表格的数据结构。SeriesDataFrame的一列。一个DataFrame可以被认为是一个系列对象的字典Dict

Python Pandas安装

使用以下命令安装Pandas:

$ pip3 install pandas

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

$ pip3 install numpy

一些例子也使用numpy

Pandas的简单例子

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

simple.py

#!/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]]

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

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开始。

change_index.py

#!/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标量序列

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

series_scalar.py

#!/usr/bin/python

import pandas as pd

s = pd.Series(5, index=[0, 1, 2, 3])
print(s)

我们有一列全是5的序列。

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

左列是索引。

Pandas series ndarray

我们可以从numpy narray创建一个series对象。

series_numpy.py

#!/usr/bin/python

import pandas as pd
import numpy as np

data = np.array(['a', 'b', 'c', 'd'])
s = pd.Series(data)

print(s)

该示例从narray中创建一列字母。

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

Pandas series dict

可以从Python字典创建一个系列。

series_dict.py

#!/usr/bin/python

import pandas as pd
import numpy as np

data = {'coins' : 22, 'pens' : 3, 'books' : 28}
s = pd.Series(data)

print(s)

该示例从项的字典创建一个series对象。

$ python series_dict.py
coins    22
pens      3
books    28
dtype: int64

索引由项的名称组成。

Pandas series retrieve

下面的示例从一个系列对象中检索值。

series_retrieve.py

#!/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 custom index

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

custom_index.py

#!/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 index, columns & values

Pandas DataFrame有三个基本部分:索引、列和值。

index_vals_cols.py

#!/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 sum and max value

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

sum_max.py

#!/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)

该示例计算最大值和值的总和。它使用numpyrange函数来生成一个值数组。

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

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

$ sum_max.py
359400
1198

Pandas读CSV

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

military_spending.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文件,包含有关各国军事开支的数据。

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

read_from_csv.py

#!/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))

因为我们有位置Pos列,所以我们对输出隐藏了索引。

$ 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

Pandas write CSV

使用to_csvDataFrame写入CSV文件。

write_csv.py

#!/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文件。

Pandas 随机行

可以用sample从数据帧中随机选择行。

random_sample.py

#!/usr/bin/python

import pandas as pd

df = pd.read_csv("military_spending.csv")

print(df.sample(3))

在本例中,我们从数据帧中打印随机的三行。

Pandas数据转置(Orient)

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

data_orient.py

#!/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'))

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

Pandas describe

describe 方法生成描述性统计,总结数据集分布的集中趋势、分散和形状,不包括NaN值。

describing.py

#!/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

Pandas Counting

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

counting.py

#!/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)

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

Pandas head and tail

使用headtail方法,我们可以显示数据帧的第一行和最后n行。

head_tail.py

#!/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 no header and index

我们可以在显示数据帧时隐藏标题和索引。

no_header_index.py

#!/usr/bin/python

import pandas as pd

df = pd.read_csv("military_spending.csv")

print(df.head(4).to_string(header=False, index=False))

通过将headerindex属性设置为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列。)

Pandas loc

loc方法允许通过标签或布尔数组访问一组行和列。

select_loc.py

#!/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

第二个示例展示了如何通过布尔数组进行选择。

select_loc2.py

#!/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

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

select_loc3.py

#!/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之间。

Pandas iloc

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

select_iloc.py

#!/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选择行和列的各种组合。

Pandas排序

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

sorting.py

#!/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

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

sorting2.py

#!/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库。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值