Matplotlib 实用指南(三)
十二、Matplotlib 动画
在前一章中,您学习了如何在 Matplotlib 中使用 3D 可视化。
在这一章中,你将学习如何使用动画。以下是您将在本章中学习的主题:
-
动画基础
-
赛璐珞图书馆
读完这一章,你将能够在 Matplotlib 和另一个有用的库中使用动画。
动画基础
在本节中,您将学习如何使用 Matplotlib 创建动画。首先,让我们为本章创建一个新笔记本。然后导入以下库:
%matplotlib qt
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
让我们定义对象,换句话说,图形、轴和绘图,如下所示:
fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)
让我们定义函数init(),它将初始化动画并为动画设置数据,如下所示:
def init():
line.set_data([], [])
return line,
让我们定义一个动画函数,如下所示:
def animate(i):
x = np.linspace(0, 4, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
该函数接受帧数作为参数(在本例中是名为i的变量),并为动画渲染帧。
现在我们已经定义了组件,让我们使用函数调用FuncAnimation()创建一个动画对象。它接受创建的函数作为参数。它还接受帧数和间隔作为参数。参数blit的自变量是True。这意味着只重画已经改变的部分。
anim = FuncAnimation(fig, animate,
init_func=init,
frames=1000,
interval=10,
blit=True)
您也可以将动画保存为 GIF 格式,如下所示:
anim.save('sine_wave.gif', writer='pillow')
图 12-1 显示了输出。
图 12-1
将正弦波可视化
您可以与动画互动,并用鼠标更改方向。在继续下一步之前,探索所有的交互可能性。
您可以创建渐进式螺旋,如下所示:
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
xdata, ydata = [], []
def animate(i):
t = 0.2*i
x = t*np.cos(t)
y = t*np.sin(t)
xdata.append(x)
ydata.append(y)
line.set_data(xdata, ydata)
return line,
anim = FuncAnimation(fig, animate,
init_func=init,
frames=3000,
interval=5,
blit=True)
图 12-2 显示了输出。
图 12-2
可视化螺旋动画
赛璐珞图书馆
你可以使用另一个简单的叫做赛璐珞的库来制作动画。让我们按如下方式安装它:
!pip3 install celluloid
您可以按如下方式导入它:
from celluloid import Camera
让我们创建一个人物和照相机对象,如下所示:
fig = plt.figure()
camera = Camera(fig)
让我们创建一个动画的帧,并用名为camera.snap()的函数将它们保存在内存中,如下所示:
for i in range(10):
plt.plot([i] * 10)
camera.snap()
让我们创建如下动画:
animation = camera.animate()
图 12-3 显示了输出。
图 12-3
使用赛璐珞库的动画
您也可以创建正弦波,如下所示:
fig, axes = plt.subplots()
camera = Camera(fig)
t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
for i in t:
plt.plot(t, np.sin(t + i), color='green')
camera.snap()
animation = camera.animate()
图 12-4 显示了输出。
图 12-4
用赛璐珞库制作正弦波动画
条形图的另一个示例如下:
fig, axes = plt.subplots()
camera = Camera(fig)
y = np.arange(5)
for i in y:
plt.bar( np.random.rand(5)*10 , y)
camera.snap()
animation = camera.animate()
图 12-5 显示了输出。
图 12-5
带赛璐珞库的条形图动画
摘要
在本章中,您学习了如何使用动画。
在下一章,你将学习如何用 Matplotlib 做更多的事情。
十三、使用 Matplotlib 实现更多可视化
在上一章中,您学习了如何在 Matplotlib 中处理动画。
在这一章中,你将学习更多使用 Matplotlib 的技巧。这一章是你到目前为止所获得的所有知识的顶点。这一章有一系列使用 Matplotlib 的技巧,我在前面的章节中没有提到。具体来说,以下是您将在本章中学习的主题:
-
将功能可视化为图像和轮廓
-
使用 3D 晕影
-
装饰散点图
-
使用时间图和信号
-
使用填充图、阶跃图和六边形图
-
使用 XKCD 样式
阅读完本章后,你将能够在 Matplotlib 中创建各种新的可视化。
将功能可视化为图像和轮廓
让我们想象一个数字函数。导入所有需要的库,如下所示:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
让我们将函数定义如下:
def f(x, y):
return (x ** 3 + y ** 2)
让我们将其形象化,如下所示:
n = 10
x = np.linspace(-3, 3, 8 * n)
y = np.linspace(-3, 3, 6 * n)
X, Y = np.meshgrid(x, y)
Z = f( X, Y )
plt.imshow(Z, interpolation='nearest',
cmap = 'cool', origin='lower')
plt.axis('off')
plt.show()
图 13-1 显示了输出。
图 13-1
将功能可视化为图像
你也可以把这个函数想象成一个轮廓。
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, f(X, Y), 8,
alpha = 0.75, cmap='hot')
C = plt.contour(X, Y, f(X, Y), 8,
colors='black')
plt.clabel(C, inline=1, fontsize=10)
plt.axis('off')
plt.show()
图 13-2 显示了输出。
图 13-2
将函数可视化为轮廓
3D 缩图
您可以按如下方式创建三维晕影可视化:
%matplotlib qt
fig = plt.figure()
ax = plt.axes(projection='3d')
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1,
cstride=1, cmap='hot')
ax.contourf(X, Y, Z, zdir='z',
offset=-2, cmap='hot')
ax.set_zlim(-2, 2)
plt.axis('off')
ax.set_zticks(())
plt.show()
图 13-3 显示了输出。
图 13-3
可视化 3D 晕影
装饰散点图
您可以使用 Matplotlib 创建装饰散点图。您需要将颜色和大小作为参数传递。这里有一个例子:
%matplotlib inline
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
color = np.arctan2(Y, X)
plt.scatter(X, Y, s=75, c=color, alpha=0.5)
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
plt.axis('off')
plt.show()
图 13-4 显示了输出。
图 13-4
可视化装饰散点图
时间图和信号
您可以将时间图和信号可视化如下:
N = 100
x = np.arange(N) # timestamps
y1 = np.random.randn(N)
y2 = np.random.randn(N)
y3 = np.random.randn(N)
y4 = np.random.randn(N)
plt.subplot(2, 1, 1)
plt.plot(x, y1)
plt.plot(x, y2, ':')
plt.grid()
plt.xlabel('Time')
plt.ylabel('y1 and y2')
plt.axis('tight')
plt.subplot(2, 1, 2)
plt.plot(x, y3)
plt.plot(x, y4, 'r')
plt.grid()
plt.xlabel('Time')
plt.ylabel('y3 and y4')
plt.axis('tight')
plt.show()
图 13-5 显示了输出。
图 13-5
可视化时间图和信号
也可以将两个信号相乘。在下面的代码示例中,我们使用同一个 x 轴来显示所有三个图表。
f = 1
t = np.arange( 0.0, 4.0, 0.01)
s1 = np.sin(2 *np.pi * f * t)
s2 = np.exp(-t)
s3 = s1 * s2
f = plt.figure()
plt.subplots_adjust(hspace=0.001)
ax1 = plt.subplot( 311 )
ax1.plot(t, s1)
plt.yticks(np.arange(-0.9, 1.0, 0.4))
plt.ylim(-1, 1)
ax2 = plt.subplot(312, sharex=ax1)
ax2.plot(t, s2)
plt.yticks(np.arange(0.1, 1.0, 0.2))
plt.ylim(0, 1)
ax3 = plt.subplot(313, sharex = ax1)
ax3.plot(t, s3)
plt.yticks(np.arange(-0.9, 1.0, 0.4))
plt.ylim(-1, 1)
xticklabels = ax1.get_xticklabels() + ax2.get_xticklabels()
plt.setp(xticklabels, visible=False)
plt.show()
图 13-6 显示了输出。
图 13-6
乘法信号
填充图
您可以按如下方式填充地块边界内的空白空间:
N = 1000
x = np.linspace(0, 1, N)
y = np.sin(4 * np.pi * x) + np.exp(-5 * x)
plt.fill(x, y, 'g', alpha = 0.8)
plt.grid(True)
plt.show()
图 13-7 显示了输出。
图 13-7
填充图
阶梯图
我们先来可视化一些正弦波。
N = 100
x = np.linspace(-np.pi, np.pi, N)
y1 = 0.5 * np.sin(3*x)
y2 = 1.25 * np.sin(2*x)
y3 = 2 * np.sin(4*x)
plt.plot(x, y1, x, y2, x, y3)
plt.show()
图 13-8 显示了输出。
图 13-8
正弦曲线
您可以将它们显示为阶跃图,如下所示:
plt.step(x, y1)
plt.step(x, y2)
plt.step(x, y3)
plt.show()
图 13-9 显示了输出。
图 13-9
带阶梯图的正弦曲线
赫克宾斯
您可以将数据显示为六边形,如下所示:
x, y = np.random.normal(size=(2, 10000))
plt.hexbin(x, y,
gridsize=20,
cmap='cool')
plt.colorbar()
plt.show()
图 13-10 显示了输出。
图 13-10
Hexbin 可视化
xcd 风格
您可以在 XKCD 样式中可视化地块。XKCD 是一部流行的网络漫画。 https://xkcd.com 是网络漫画的主页。
y = np.random.randn(1000)
plt.xkcd()
plt.hist(y)
plt.show()
图 13-11 显示了输出。
图 13-11
XKCD 直方图
另一个例子如下:
y = np.random.randn(1000)
plt.xkcd()
plt.hist(y, bins = 30,
range=[-3.5, 3.5],
facecolor='r',
alpha=0.6,
edgecolor='k')
plt.grid()
plt.show()
图 13-12 显示了输出。
图 13-12
另一个 XKCD 直方图
您也可以用同样的方式显示 2D 直方图,如下所示:
data = np.random.randn(1000, 1000)
plt.xkcd()
plt.hist2d(data[0], data[1])
plt.show()
图 13-13 显示了输出。
图 13-13
第三个 XKCD 直方图
摘要
在本章中,您学习了如何使用 Matplotlib 处理一些额外的可视化技术。
在下一章中,你将熟悉一个名为 Pandas 的数据科学库。
十四、Pandas 简介
在前一章中,您学习了许多 Matplotlib 技术。现在,您将学习如何使用数据科学和数据可视化中常见的另一个库。
在这一章中,我们将关注科学 Python 生态系统中主要数据科学和分析库的基础知识:Pandas。您将了解这个库中的数据结构。以下是本章中的主题:
-
Pandas 简介
-
Pandas 系列
-
Pandas 的数据帧
读完这一章后,你会很舒服地用 Pandas 做基本的任务。
Pandas 简介
Pandas 是科学 Python 生态系统中的数据分析组件。事实上,它是科学 Python 生态系统不可或缺的一部分。它带有多用途的数据结构和管理它们的例程。它带有多用途的数据结构和管理这些数据结构的例程。
让我们通过在 Jupyter 笔记本中运行以下命令在计算机上安装 Pandas:
!pip3 install pandas
您可以通过运行以下命令将其导入到当前会话中:
import pandas as pd
你可以在 https://pandas.pydata.org/ 了解更多关于 Pandas 的信息。
Pandas 系列
系列是带有标签的一维数组。它可以保存任何类型的数据。这些标签统称为索引。
您可以按如下方式创建系列:
s1 = pd.Series([3, 2, 1 , 75, -3.14])
您可以按如下方式检查其数据类型:
type(s1)
以下是输出:
<class 'pandas.core.series.Series'>
您可以看到与数据相关联的值和索引,如下所示:
print(s1)
以下是输出:
0 3.00
1 2.00
2 1.00
3 75.00
4 -3.14
dtype: float64
您可以明确地提及数据类型,如下所示:
s2 = pd.Series([3, 2, 1 , 75, -3.14], dtype=np.float32)
print(s2)
您可以将列表作为参数传递给构造函数来创建序列,如下所示:
x = [3, 2, 1 , 75, -3.14]
s3 = pd.Series(x)
您甚至可以将 NumPy Ndarray 作为参数传递给构造函数来创建序列,如下所示:
import numpy as np
y = np.array(x)
s4 = pd.Series(y)
您可以看到如下值:
print(s4.values)
以下是输出:
[ 3\. 2\. 1\. 75\. -3.14]
您可以按如下方式检索索引:
print(s4.index)
输出如下所示:
RangeIndex(start=0, stop=5, step=1)
您可以按如下方式分配自定义索引:
s5 = pd.Series( x, index = ['a', 'b', 'c', 'd', 'e'])
print(s5)
输出如下所示:
a 3.00
b 2.00
c 1.00
d 75.00
e -3.14
dtype: float64
系列的基本操作
您可以对系列图像执行一些基本操作。例如,您可以按如下方式显示负数:
print(s5[s5 < 0])
输出如下所示:
e -3.14
dtype: float64
您可以按如下方式检索正数:
print(s5[s5 > 0])
输出如下所示:
a 3.0
b 2.0
c 1.0
d 75.0
dtype: float64
这些是比较操作的例子。您可以执行算术运算,例如乘法,如下所示:
c = 3
print ( s5 * c )
输出如下所示:
a 9.00
b 6.00
c 3.00
d 225.00
e -9.42
dtype: float64
Pandas 的数据帧
数据帧是一种二维的带标签的数据结构,其列可以是不同的数据类型。您可以从系列、数据阵列、列表和字典创建数据框架。
数据帧有标签,统称为索引。您可以轻松查看和操作数据框中的数据。数据以矩形网格格式存储在数据帧中。
您可以从列表中创建数据帧,如下所示。以下是字典:
data = {'city': ['Delhi', 'Delhi', 'Delhi',
'Bangalore', 'Bangalore', 'Bangalore'],
'year': [2020, 2021, 2022, 2020, 2021, 2022,],
'population': [10.0, 10.1, 10.2, 5.2, 5.3, 5.5]}
让我们由此创建一个数据帧,如下所示:
df1 = pd.DataFrame(data)
print(df1)
输出如下所示:
city year population
0 Delhi 2020 10.0
1 Delhi 2021 10.1
2 Delhi 2022 10.2
3 Bangalore 2020 5.2
4 Bangalore 2021 5.3
5 Bangalore 2022 5.5
您可以看到前五条记录如下:
df1.head()
输出如下所示:
city year population
0 Delhi 2020 10.0
1 Delhi 2021 10.1
2 Delhi 2022 10.2
3 Bangalore 2020 5.2
4 Bangalore 2021 5.3
您还可以将其他数字作为参数传递给函数head(),它将显示数据帧中的许多顶级记录。同样,您可以使用df1.tail()来查看最后的记录。它还将 5 作为默认参数,但是您可以自定义传递给它的参数。
您可以创建具有特定列顺序的数据帧,如下所示:
df2 = pd.DataFrame(data, columns=['year', 'city', 'population'])
print(df2)
输出如下所示:
year city population
0 2020 Delhi 10.0
1 2021 Delhi 10.1
2 2022 Delhi 10.2
3 2020 Bangalore 5.2
4 2021 Bangalore 5.3
5 2022 Bangalore 5.5
让我们创建一个带有附加列和自定义索引的数据帧,如下所示:
df3 = pd.DataFrame(data, columns=['year', 'city', 'population', 'GDP'],
index = ['one', 'two', 'three', 'four', 'five', 'six'])
print(df3)
以下是新的数据框架:
year city population GDP
one 2020 Delhi 10.0 NaN
two 2021 Delhi 10.1 NaN
three 2022 Delhi 10.2 NaN
four 2020 Bangalore 5.2 NaN
five 2021 Bangalore 5.3 NaN
six 2022 Bangalore 5.5 NaN
您可以按如下方式打印列列表:
print(df3.columns)
输出如下所示:
Index(['year', 'city', 'population', 'GDP'], dtype='object')
您可以按如下方式打印索引列表:
print(df3.index)
输出如下所示:
Index(['one', 'two', 'three', 'four', 'five', 'six'], dtype='object')
您可以使用以下语句查看列的数据:
print(df3.year)
或者也可以使用下面的语句:
print(df3['year'])
以下是输出:
one 2020
two 2021
three 2022
four 2020
five 2021
six 2022
Name: year, dtype: int64
您可以使用以下语句查看列的数据类型:
print(df3['year'].dtype)
或者,您可以使用以下方法:
print(df3.year.dtype)
输出如下所示:
int64
您可以看到所有列的数据类型如下:
print(df3.dtypes)
输出如下所示:
year int64
city object
population float64
GDP object
dtype: object
您可以使用索引检索任何记录,如下所示:
df3.loc['one']
输出如下所示:
year 2020
city Delhi
population 10.0
GDP NaN
Name: one, dtype: object
您可以为列的所有成员分配相同的值,如下所示:
df3.GDP = 10
print(df3)
输出如下所示:
year city population GDP
one 2020 Delhi 10.0 10
two 2021 Delhi 10.1 10
three 2022 Delhi 10.2 10
four 2020 Bangalore 5.2 10
five 2021 Bangalore 5.3 10
six 2022 Bangalore 5.5 10
您可以为列GDP分配一个 Ndarray,如下所示:
import numpy as np
df3.GDP = np.arange(6)
print(df3)
输出如下所示:
year city population GDP
one 2020 Delhi 10.0 0
two 2021 Delhi 10.1 1
three 2022 Delhi 10.2 2
four 2020 Bangalore 5.2 3
five 2021 Bangalore 5.3 4
six 2022 Bangalore 5.5 5
您还可以为其分配一个列表,如下所示:
df3.GDP = [3, 2, 0, 9, -0.4, 7]
print(df3)
输出如下所示:
year city population GDP
one 2020 Delhi 10.0 3.0
two 2021 Delhi 10.1 2.0
three 2022 Delhi 10.2 0.0
four 2020 Bangalore 5.2 9.0
five 2021 Bangalore 5.3 -0.4
six 2022 Bangalore 5.5 7.0
让我们给它分配一个系列,如下所示:
val = pd.Series([-1.4, 1.5, -1.3], index=['two', 'four', 'five'])
df3.GDP = val
print(df3)
输出如下所示:
year city population GDP
one 2020 Delhi 10.0 NaN
two 2021 Delhi 10.1 -1.4
three 2022 Delhi 10.2 NaN
four 2020 Bangalore 5.2 1.5
five 2021 Bangalore 5.3 -1.3
six 2022 Bangalore 5.5 NaN
摘要
在这一章中,你探索了科学 Python 生态系统的 Pandas 数据科学库的基础。您学习了创建和使用基本的 Pandas 数据结构的基础知识,它们是 series 和 dataframe。
在下一章中,您将学习如何使用库 NumPy、Pandas 和 Matplotlib 以编程方式读取以各种格式存储的数据。
十五、数据采集
在前一章中,您学习了使用两个 Pandas 数据结构的基础知识,即 series 和 dataframe。
这一章着重于使用你到目前为止学习过的所有库(NumPy、Matplotlib 和 Pandas)用 Python 获取数据。以下是您将在本章中了解的主题:
-
处理纯文本文件
-
用 Python 处理 CSV 文件
-
使用 Python 和 Excel
-
用 NumPy 读写文件
-
用 NumPy 从 CSV 文件中读取数据
-
使用 Matplotlib CBook
-
从 CSV 文件中读取数据
-
从 Excel 文件中读取数据
-
从 JSON 文件中读取数据
-
从 Pickle 文件中读取数据
-
从网上读取数据
-
从关系数据库中读取数据
-
从剪贴板读取数据
读完这一章后,你将可以轻松地从各种文件格式中读取数据并保存它。
纯文本文件处理
让我们学习如何从一个纯文本文件中读取数据,以及将数据写入到一个纯文本文件中。Python 自带读写纯文本文件的功能。我们有四种打开文件的模式,如下所示:
-
w:写 -
r:阅读 -
a:追加 -
r+:读写模式
您可以按如下方式使用它们(一次一个):
f = open('testfile.txt', 'w')
print(f)
这段代码以写模式打开testfile.txt文件。如果文件不存在,那么 Python 会在磁盘上的当前位置创建这个文件。如果文件已经存在,它会覆盖文件的内容。前面的代码打印 file 对象,如下所示:
<_io.TextIOWrapper name='testfile.txt' mode='w' encoding='cp1252'>
让我们向文件中写入一些数据。在这种情况下,数据由多字符字符串组成。
f.write('This is a test string.\n')
f.write('This is the middle line.\n')
f.write('This is the last line.')
您可以按如下方式关闭文件对象(也称为文件句柄):
f.close()
您知道再次以写模式打开文件会覆盖其数据。因此,这一次,让我们以追加模式打开同一个文件,如下所示:
f = open('testfile.txt', 'a')
f.write('\nThis is the appended line.')
f.close()
我们在文件中写入一行,然后关闭文件。让我们读取数据并将其打印如下:
f = open('testfile.txt', 'r')
print(f.read())
f.close()
输出如下所示:
This is a test string.
This is the middle line.
This is the last line.
This is the appended line
您可以检索列表中的行(文件中的每一行都对应于列表中的一个元素),如下所示:
f = open('testfile.txt', 'r')
print(f.readlines())
f.close()
输出如下所示:
['This is a test string.\n', 'This is the middle line.\n', 'This is the last line.\n', 'This is the appended line.']
您也可以按如下方式逐行检索文件中的数据:
f = open('testfile.txt', 'r')
for line in f:
print(line)
f.close()
输出如下所示:
This is a test string.
This is the middle line.
This is the last line.
This is the appended line.
用 Python 处理 CSV 文件
让我们了解一些关于逗号分隔文件(CSV)格式的事情。CSV 文件以纯文本格式存储数据,数据项或者是固定长度,或者由逗号(,)、竖线(|)或冒号(:)等分隔符分隔。最常见的 CSV 格式使用逗号作为分隔符,很多时候第一行用于存储列名。
在本节中,您将学习如何用 Python 3 处理 CSV 文件。Python 3 附带了一个内置库来处理 CSV 文件。您不需要安装任何东西。您可以按如下方式导入库:
import csv
您可以在读取模式下以纯文本文件的形式打开该文件,如下所示:
file = open('test.csv', 'r')
print(file)
打开文件后,可以将文件句柄传递给例程csv.reader(),如下所示:
csvfile = csv.reader(file, delimiter=',')
print(csvfile)
这将打印对象的值,如下所示:
<_csv.reader object at 0x0590AC68>
您可以按如下方式逐行检索数据:
for row in csvfile:
print(row)
这会产生以下输出:
['Banana', 'Yellow', '250']
['Orange', 'Orange', '200']
['Grapes', 'Green', '400']
['Tomato', 'Red', '100']
['Spinach', 'Green', '40']
['Potatoes', 'Gray', '400']
['Rice', 'White', '300']
['Rice', 'Brown', '400']
['Wheat', 'Brown', '500']
['Barley', 'Yellow', '500']
您可以单独显示元素,如下所示:
for row in csvfile:
for element in row:
print(element)
输出如下所示:
Banana
Yellow
250
Orange
Orange
200
Grapes
Green
400
Tomato
Red
100
Spinach
Green
40
Potatoes
Gray
400
Rice
White
300
Rice
Brown
400
Wheat
Brown
500
Barley
Yellow
500
让我们关闭文件句柄,如下所示:
file.close()
Python 和 Excel
让我们看看如何从 Excel 中读取数据。为此你需要一个外部库。以下代码安装我们将在本节中使用的库:
!pip3 install openpyxl
您可以按如下方式导入它:
import openpyxl
您可以按如下方式打开 Excel 文件:
wb = openpyxl.load_workbook('test.xlsx')
print(wb)
print(type(wb))
输出如下所示:
<openpyxl.workbook.workbook.Workbook object at 0x0E87F7D8>
<class 'openpyxl.workbook.workbook.Workbook'>
您可以按如下方式检索所有工作表的名称:
print(wb.sheetnames)
输出如下所示:
['Sheet1', 'Sheet2', 'Sheet3']
您可以按如下方式选择图纸:
currSheet = wb['Sheet1']
print(currSheet)
print(type(currSheet))
输出如下所示:
<Worksheet "Sheet1">
<class 'openpyxl.worksheet.worksheet.Worksheet'>
同样,下面的代码具有相同的效果:
currSheet = wb[wb.sheetnames[0]]
print(currSheet)
print(type(currSheet))
您可以打印当前工作表的名称,如下所示:
print(currSheet.title)
输出如下所示:
Sheet1
您可以按如下方式打印单元格的值:
var1 = currSheet['A1']
print(var1.value)
输出如下所示:
Food Item
进行相同活动的另一种方法如下:
print(currSheet['B1'].value)
您可以用另一种方式来完成,如下所示:
var2 = currSheet.cell(row=2, column=2)
print(var2.value)
行数和列数可以如下获得:
print(currSheet.max_row)
print(currSheet.max_column)
输出如下所示:
11
3
让我们打印电子表格中的所有数据,如下所示:
for i in range(currSheet.max_row):
print('---Beginning of Row---')
for j in range(currSheet.max_column):
var = currSheet.cell(row=i+1, column=j+1)
print(var.value)
print('---End of Row---')
输出很长,所以我在这里截断了它。请运行代码亲自查看。
用 NumPy 读写文件
让我们看看如何用 NumPy 读写文件。让我们用 NumPy 创建一个数据集,如下所示:
import numpy as np
x = np.arange(100)
print(x)
输出如下所示:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99]
您可以将其保存到一个文件(NumPy 数据格式),如下所示:
np.save('test.npy', x)
您可以将数据从文件加载到变量中,如下所示:
data = np.load('test.npy')
print(data)
输出如下所示:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99]
用 NumPy 从 CSV 文件中读取数据
CSV 文件也可以用 NumPy 读取,如下所示:
import numpy as np
# Reads only numeric data
data = np.loadtxt('data.csv', delimiter=',')
print(data)
输出如下所示:
[[ 0\. 1\. 18\. 2.]
[ 1\. 6\. 1\. 3.]
[ 2\. 3\. 154\. 0.]
[ 4\. 978\. 3\. 6.]
[ 5\. 2\. 41\. 45.]
[ 6\. 67\. 2\. 3.]
[ 7\. 5\. 67\. 2.]]
您也可以跳过行和列,如下所示:
data = np.loadtxt('data.csv', delimiter=',',
skiprows=3, usecols=[1, 3])
print(data)
输出如下所示:
[[978\. 6.]
[ 2\. 45.]
[ 67\. 3.]
[ 5\. 2.]]
Matplotlib CBook
您可以读取以 Matplotlib 的 CBook 格式存储的数据。Matplotlib 附带了一些这种格式的示例文件。让我们看看如何读取数据:
import matplotlib.cbook as cbook
datafile = cbook.get_sample_data('aapl.npz')
r = np.load(datafile)
print(r.files)
这将打印数据文件的名称,如下所示:
['price_data']
让我们从该数据文件中读取数据:
print(r['price_data'])
这显示了苹果股价数据如下:
[('1984-09-07', 26.5 , 26.87, 26.25, 26.5 , 2981600, 3.02)
('1984-09-10', 26.5 , 26.62, 25.87, 26.37, 2346400, 3.01)
('1984-09-11', 26.62, 27.37, 26.62, 26.87, 5444000, 3.07) ...
('2008-10-10', 85.7 , 100\. , 85\. , 96.8 , 79260700, 96.8 )
('2008-10-13', 104.55, 110.53, 101.02, 110.26, 54967000, 110.26)
('2008-10-14', 116.26, 116.4 , 103.14, 104.08, 70749800, 104.08)]
从 CSV 读取数据
如前所述,CSV 文件包含用逗号分隔的值。您可以使用 Pandas 中的多功能功能read_csv()来读取网络上或本地/网络磁盘上的 CSV 文件。以下是我们将在本演示中使用的 CSV 文件的内容:
rank,discipline,phd,service,sex,salary
Prof,B,56,49,Male,186960
Prof,A,12,6,Male,93000
Prof,A,23,20,Male,110515
Prof,A,40,31,Male,131205
Prof,B,20,18,Male,104800
Prof,A,20,20,Male,122400
AssocProf,A,20,17,Male,81285
第一行是标题行。大多数 CSV 文件都有一个标题行,尽管这不是必需的。如您所见,这些值由逗号分隔。这是 CSV 文件的常见格式。根据系统和应用程序的不同,您可以使用各种分隔符,如空格、分号(;),或者是管道(|)。此外,CSV 文件可以使用固定数量的字符在列中存储数据。在本例中,如前所述,我们使用最常见的 CSV 格式存储数据。
让我们学习如何用 Pandas 从这样的文件中读取数据。为本章创建新笔记本。
按如下方式导入 Pandas 库:
import pandas as pd
让我们阅读一个位于 Web 上的 CSV 文件,如下所示:
df1 = pd.read_csv("http://rcs.bu.edu/examples/python/data_analysis/Salaries.csv")
print(df1)
您还可以读取存储在本地磁盘上的 CSV,如下所示:
df2 = pd.read_csv("Salaries.csv")
print(df2)
您也可以将数据帧的数据转储到磁盘位置的 CSV 文件中,如下所示:
df2.to_csv('output.csv', index=True, header=False)
该代码将在磁盘的当前目录下创建一个 CSV 文件。
从 Excel 文件中读取数据
要将 Excel 文件中的数据读入 Pandas dataframe,您需要一个外部包的支持。让我们安装一个包,如下所示:
!pip3 install xlrd
现在我们来读取存储在磁盘上的 Excel 文件,如下:
excel_file = 'test.xlsx'
df1 = pd.read_excel(excel_file)
在这里(在前面的例子中也是如此),文件存储在与笔记本文件相同的目录中。如果需要读取任何其他位置的文件,必须指定该文件的完整路径。前面的代码在执行时会将 Excel 文件的内容加载到 Pandas 数据帧中。您可以使用下面一行代码来查看内容:
print(df1)
图 15-1 显示了输出。
图 15-1
Excel 表格中的数据
从 JSON 读取数据
您可以将 JSON 字符串的数据读入 dataframe,如下所示。首先创建一个 JSON 字符串。
obj = """
{"name": "Ashwin",
"places_lived": ["Nashik", "Hyderabad", "Bangalore"],
"pet": null,
"siblings": [{"name": "Scott", "age": 30, "pets": ["Zeus", "Zuko"]},
{"name": "Katie", "age": 38,
"pets": ["Sixes", "Stache", "Cisco"]}]
}
"""
您可以按如下方式打印该字符串:
print(obj)
您还可以检查变量的类型(它是 JSON 格式的字符串),如下所示:
print(type(obj))
您可以将这个 JSON 格式的字符串转换成字典,如下所示:
import json
result = json.loads(obj)
print(result)
让我们检查新创建的变量的数据类型,如下所示:
print(type(result))
这将产生以下结果:
<class 'dict'>
让我们将数据加载到数据帧中,如下所示:
df1 = pd.DataFrame(result['siblings'], columns=['name', 'age'])
print(df1)
输出如下所示:
name age
0 Scott 30
1 Katie 38
您还可以从 JSON 文件中读取数据,如下所示:
df2 = pd.read_json('example_2.json')
print(df2)
这就是将 JSON 数据读入数据帧的方法。
从 Pickle 文件中读取数据
在 Python 编程中,Pickle 用于序列化和反序列化 Python 对象。您可以将 Pandas 数据帧存储到磁盘上的 Pickle 文件中,如下所示:
data = [1, 2, 3, 4, 5]
df1 = pd.DataFrame(data)
print(df1)
df1.to_pickle('mypickle')
您可以从存储在磁盘上的 Pickle 文件中读取数据,如下所示:
df2 = pd.read_pickle('mypickle')
print(df2)
从网上读取数据
让我们从网上读取数据。为此,您将需要几个库。您可以按如下方式安装它们:
!pip3 install lxml html5lib BeautifulSoup4
您可以阅读位于 Web 上的 HTML 文件,如下所示:
df1 = pd.read_html('https://www.google.com/')
让我们按如下方式获取对象和数据的详细信息:
print(df1)
len(df1)
type(df1)
df1[0].head()
您还可以解析检索到的 HTML 文本,并从标记中获取重要信息,如下所示:
from lxml import objectify
from io import StringIO
下面是一个 HTML 标记字符串和解析它的方法,如下所示:
tag = '<a href="http://www.google.com/">Google</a>'
root = objectify.parse(StringIO(tag)).getroot()
您按如下方式检索该对象的根和文本:
print(root)
root.get('href')
print(root.text)
这将产生以下输出:
Google
Google
与 Web API 交互
让我们学习与 web API 交互,以检索数据并将其存储到 Pandas 数据帧中。按如下方式安装必要的库:
!pip3 install requests
让我们按如下方式导入库:
import requests
让我们创建如下 URL 字符串:
url='https://api.github.com/repos/pandas-dev/pandas/issues'
您可以使用以编程方式发出的 HTTP GET 请求从 URL 获取数据,如下所示:
resp = requests.get(url)
您可以检查响应代码及其数据类型,如下所示:
print(resp)
print(type(resp))
输出如下所示:
<Response [200]>
<class 'requests.models.Response'>
HTTP 响应代码 200 代表检索信息成功。您可以按如下方式检索实际信息:
data = resp.json()
print(type(data))
这将是一个列表,如下所示:
<class 'list'>
您可以将其转换为数据帧,如下所示:
output = pd.DataFrame(data, columns=['number', 'title', 'labels', 'state'])
print(output)
图 15-2 显示了输出。
图 15-2
HTTPS 的数据得到了回应
这就是你如何处理网上的数据。
从关系数据库表中读取数据
您可以读取存储在关系数据库(如 MySQL 或 MariaDB)的表中的数据。您可以通过以下网址了解有关安装和使用的更多信息:
https://www.mysql.com/
https://mariadb.org/
您必须安装外部库,如下所示:
!pip3 install pymysql
然后,您需要将库导入笔记本,如下所示:
import pymysql
您可以连接到 MySQL 或 MariaDB 数据库实例,如下所示:
db = pymysql.connect(host="localhost", user="root",
password="test123", database="world")
然后您可以将一个SELECT查询的输出读入一个数据帧,如下所示:
df1 = pd.read_sql('select * from country', db)
print(df1)
这产生了如图 15-3 所示的输出。
图 15-3
MySQL/MariaDB 表中的数据
从剪贴板读取数据
您可以读取存储在剪贴板上的数据。剪贴板是计算机主内存(RAM)中的一个临时且未命名的缓冲区,一些操作系统为程序内部和程序之间的数据短期存储和传输提供该缓冲区。例如,无论何时从文件中复制文本数据,它都会存储在操作系统的剪贴板上。
通过选择下列数据并按下键盘上的 Ctrl+C 按钮,将这些数据复制到计算机的剪贴板中。
A B C
x 1 2 a
y 2 3 b
z 3 4 c
您可以使用以下代码将其加载到 Pandas 数据帧中:
df = pd.read_clipboard()
您还可以通过编程方式将数据复制到剪贴板上,如下所示:
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3))
df.to_clipboard()
您可以通过以编程方式将剪贴板读入 dataframe(如前所述)来查看这些数据,也可以使用 Ctrl+V 命令将其粘贴到文本编辑器中,如 Notepad(在 Windows 上)或 Leafpad 或 gedit(在 Linux 上)。
摘要
在本章中,您学习了如何从多种文件格式中读取数据,以及如何将数据加载到 Python 变量中。
在下一章中,您将学习如何使用 Matplotlib 可视化 Pandas 数据。