Python 金融编程第二版(GPT 重译)(二)(5)

简介: Python 金融编程第二版(GPT 重译)(二)

Python 金融编程第二版(GPT 重译)(二)(4)https://developer.aliyun.com/article/1559310


合并

虽然连接操作是基于要连接的 DataFrame 对象的索引进行的,但合并操作通常是在两个数据集之间共享的列上进行的。为此,将新列 C 添加到原始的两个 DataFrame 对象中:

In [105]: c = pd.Series([250, 150, 50], index=['b', 'd', 'c'])
          df1['C'] = c
          df2['C'] = c
In [106]: df1
Out[106]:      A      C
          a  100    NaN
          b  200  250.0
          c  300   50.0
          d  400  150.0
In [107]: df2
Out[107]:      B      C
          f  200    NaN
          b  150  250.0
          d   50  150.0

默认情况下,此情况下的合并操作基于单个共享列 C 进行。然而,还有其他选项可用。

In [108]: pd.merge(df1, df2)  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[108]:      A      C    B
          0  100    NaN  200
          1  200  250.0  150
          2  400  150.0   50
In [109]: pd.merge(df1, df2, on='C')  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[109]:      A      C    B
          0  100    NaN  200
          1  200  250.0  150
          2  400  150.0   50
In [110]: pd.merge(df1, df2, how='outer')  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[110]:      A      C    B
          0  100    NaN  200
          1  200  250.0  150
          2  300   50.0  NaN
          3  400  150.0   50


默认在列 C 上合并。


外部合并也是可能的,保留所有数据行。

还有许多其他类型的合并操作可用,以下代码示例了其中的一些:

In [111]: pd.merge(df1, df2, left_on='A', right_on='B')
Out[111]:      A    C_x    B  C_y
          0  200  250.0  200  NaN
In [112]: pd.merge(df1, df2, left_on='A', right_on='B', how='outer')
Out[112]:      A    C_x    B    C_y
          0  100    NaN  NaN    NaN
          1  200  250.0  200    NaN
          2  300   50.0  NaN    NaN
          3  400  150.0  NaN    NaN
          4  NaN    NaN  150  250.0
          5  NaN    NaN   50  150.0
In [113]: pd.merge(df1, df2, left_index=True, right_index=True)
Out[113]:      A    C_x    B    C_y
          b  200  250.0  150  250.0
          d  400  150.0   50  150.0
In [114]: pd.merge(df1, df2, on='C', left_index=True)
Out[114]:      A      C    B
          f  100    NaN  200
          b  200  250.0  150
          d  400  150.0   50
In [115]: pd.merge(df1, df2, on='C', right_index=True)
Out[115]:      A      C    B
          a  100    NaN  200
          b  200  250.0  150
          d  400  150.0   50
In [116]: pd.merge(df1, df2, on='C', left_index=True, right_index=True)
Out[116]:      A      C    B
          b  200  250.0  150
          d  400  150.0   50

性能方面

本章中的许多示例说明了使用 pandas 可以实现相同目标的多个选项。本节比较了用于逐元素添加两列的此类选项。首先,使用 NumPy 生成的数据集。

In [117]: data = np.random.standard_normal((1000000, 2))  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [118]: data.nbytes  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[118]: 16000000
In [119]: df = pd.DataFrame(data, columns=['x', 'y'])  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [120]: df.info()  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
          <class 'pandas.core.frame.DataFrame'>
          RangeIndex: 1000000 entries, 0 to 999999
          Data columns (total 2 columns):
          x    1000000 non-null float64
          y    1000000 non-null float64
          dtypes: float64(2)
          memory usage: 15.3 MB


带有随机数字的 ndarray 对象。


带有随机数字的 DataFrame 对象。

第二,一些完成任务的性能值的选项。

In [121]: %time res = df['x'] + df['y']  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
          CPU times: user 5.68 ms, sys: 14.5 ms, total: 20.1 ms
          Wall time: 4.06 ms
In [122]: res[:3]
Out[122]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
In [123]: %time res = df.sum(axis=1)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
          CPU times: user 44 ms, sys: 14.9 ms, total: 58.9 ms
          Wall time: 57.6 ms
In [124]: res[:3]
Out[124]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
In [125]: %time res = df.values.sum(axis=1)  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
          CPU times: user 16.1 ms, sys: 1.74 ms, total: 17.8 ms
          Wall time: 16.6 ms
In [126]: res[:3]
Out[126]: array([ 0.3872424 , -0.96934273, -0.86315944])
In [127]: %time res = np.sum(df, axis=1)  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
          CPU times: user 39.7 ms, sys: 8.91 ms, total: 48.7 ms
          Wall time: 47.7 ms
In [128]: res[:3]
Out[128]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
In [129]: %time res = np.sum(df.values, axis=1)  ![5](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/5.png)
          CPU times: user 16.1 ms, sys: 1.78 ms, total: 17.9 ms
          Wall time: 16.6 ms
In [130]: res[:3]
Out[130]: array([ 0.3872424 , -0.96934273, -0.86315944])


直接操作列(Series对象)是最快的方法。


这通过在 DataFrame 对象上调用 sum() 方法来计算总和。


这通过在 ndarray 对象上调用 sum() 方法来计算总和。


这通过在 DataFrame 对象上调用 np.sum() 方法来计算总和。


这通过在 ndarray 对象上使用通用函数 np.sum() 方法来计算总和。

最后,更多基于 eval()apply() 方法的选项。

In [131]: %time res = df.eval('x + y')  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
          CPU times: user 13.3 ms, sys: 15.6 ms, total: 28.9 ms
          Wall time: 18.5 ms
In [132]: res[:3]
Out[132]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
In [133]: %time res = df.apply(lambda row: row['x'] + row['y'], axis=1)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
          CPU times: user 22 s, sys: 71 ms, total: 22.1 s
          Wall time: 22.1 s
In [134]: res[:3]
Out[134]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
# tag::PD_34[]


eval() 是专门用于评估(复杂)数值表达式的方法;可以直接访问列。


最慢的选项是逐行使用 apply() 方法;这就像在 Python 级别上循环遍历所有行。

注意

pandas 通常提供多种选项来实现相同的目标。如果不确定,应该比较一些选项,以确保在时间紧迫时获得最佳性能。在简单示例中,执行时间相差数个数量级。

结论

pandas 是数据分析的强大工具,并已成为所谓 PyData 栈的核心包。它的 DataFrame 类特别适用于处理任何类型的表格数据。对这种对象的大多数操作都是矢量化的,这不仅使代码简洁,而且通常性能很高,与 NumPy 的情况一样。此外,pandas 还使得处理不完整的数据集变得方便,例如,使用 NumPy 并不那么方便。在本书的许多后续章节中,pandasDataFrame 类将是核心,当需要时还将使用和说明其他功能。

进一步阅读

pandas 是一个文档齐全的开源项目,既有在线文档,也有可供下载的 PDF 版本。¹。以下页面提供了所有资源:

至于 NumPy,在书籍形式上推荐的参考资料是:

  • McKinney, Wes (2017): Python 数据分析. 第二版, O’Reilly, 北京等地。
  • VanderPlas, Jake (2016): Python 数据科学手册. O’Reilly, 北京等地。

¹ 在撰写本文时,PDF 版本共有 2,207 页(版本 0.21.1)。

2 -0.863159

dtype: float64

In [125]: %time res = df.values.sum(axis=1)

CPU times: user 16.1 ms, sys: 1.74 ms, total: 17.8 ms
      Wall time: 16.6 ms

In [126]: res[:3]

Out[126]: array([ 0.3872424 , -0.96934273, -0.86315944])

In [127]: %time res = np.sum(df, axis=1)

CPU times: user 39.7 ms, sys: 8.91 ms, total: 48.7 ms
      Wall time: 47.7 ms

In [128]: res[:3]

Out[128]: 0 0.387242

1 -0.969343

2 -0.863159

dtype: float64

In [129]: %time res = np.sum(df.values, axis=1)

CPU times: user 16.1 ms, sys: 1.78 ms, total: 17.9 ms
      Wall time: 16.6 ms

In [130]: res[:3]

Out[130]: array([ 0.3872424 , -0.96934273, -0.86315944])

[外链图片转存中...(img-rjeMDAFN-1717935513102)]
直接操作列(`Series`对象)是最快的方法。
[外链图片转存中...(img-TeYber2X-1717935513102)]
这通过在 `DataFrame` 对象上调用 `sum()` 方法来计算总和。
[外链图片转存中...(img-r8epalL2-1717935513102)]
这通过在 `ndarray` 对象上调用 `sum()` 方法来计算总和。
[外链图片转存中...(img-tN3j1PId-1717935513102)]
这通过在 `DataFrame` 对象上调用 `np.sum()` 方法来计算总和。
[外链图片转存中...(img-DuFuJDwd-1717935513102)]
这通过在 `ndarray` 对象上使用通用函数 `np.sum()` 方法来计算总和。
最后,更多基于 `eval()` 和 `apply()` 方法的选项。
```py
In [131]: %time res = df.eval('x + y')  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
          CPU times: user 13.3 ms, sys: 15.6 ms, total: 28.9 ms
          Wall time: 18.5 ms
In [132]: res[:3]
Out[132]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
In [133]: %time res = df.apply(lambda row: row['x'] + row['y'], axis=1)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
          CPU times: user 22 s, sys: 71 ms, total: 22.1 s
          Wall time: 22.1 s
In [134]: res[:3]
Out[134]: 0    0.387242
          1   -0.969343
          2   -0.863159
          dtype: float64
# tag::PD_34[]

[外链图片转存中…(img-c1dcFfnu-1717935513102)]

eval() 是专门用于评估(复杂)数值表达式的方法;可以直接访问列。

[外链图片转存中…(img-3htITLCT-1717935513103)]

最慢的选项是逐行使用 apply() 方法;这就像在 Python 级别上循环遍历所有行。

注意

pandas 通常提供多种选项来实现相同的目标。如果不确定,应该比较一些选项,以确保在时间紧迫时获得最佳性能。在简单示例中,执行时间相差数个数量级。

结论

pandas 是数据分析的强大工具,并已成为所谓 PyData 栈的核心包。它的 DataFrame 类特别适用于处理任何类型的表格数据。对这种对象的大多数操作都是矢量化的,这不仅使代码简洁,而且通常性能很高,与 NumPy 的情况一样。此外,pandas 还使得处理不完整的数据集变得方便,例如,使用 NumPy 并不那么方便。在本书的许多后续章节中,pandasDataFrame 类将是核心,当需要时还将使用和说明其他功能。

进一步阅读

pandas 是一个文档齐全的开源项目,既有在线文档,也有可供下载的 PDF 版本。¹。以下页面提供了所有资源:

至于 NumPy,在书籍形式上推荐的参考资料是:

  • McKinney, Wes (2017): Python 数据分析. 第二版, O’Reilly, 北京等地。
  • VanderPlas, Jake (2016): Python 数据科学手册. O’Reilly, 北京等地。

¹ 在撰写本文时,PDF 版本共有 2,207 页(版本 0.21.1)。

相关文章
|
2天前
|
存储 机器学习/深度学习 关系型数据库
Python 金融编程第二版(四)(5)
Python 金融编程第二版(四)
8 0
|
2天前
|
存储 SQL 数据库
Python 金融编程第二版(四)(4)
Python 金融编程第二版(四)
8 0
|
2天前
|
SQL 存储 数据库
Python 金融编程第二版(四)(3)
Python 金融编程第二版(四)
8 0
|
2天前
|
存储 分布式计算 数据可视化
Python 金融编程第二版(四)(2)
Python 金融编程第二版(四)
10 0
|
2天前
|
存储 SQL 数据可视化
Python 金融编程第二版(四)(1)
Python 金融编程第二版(四)
9 0
|
2天前
|
数据可视化 Python
Python 金融编程第二版(三)(4)
Python 金融编程第二版(三)
12 2
|
2天前
|
存储 索引 Python
Python 金融编程第二版(二)(1)
Python 金融编程第二版(二)
9 2
|
2天前
|
存储 算法 数据建模
Python 金融编程第二版(一)(5)
Python 金融编程第二版(一)
13 2
|
2天前
|
存储 数据可视化 API
Python 金融编程第二版(三)(5)
Python 金融编程第二版(三)
8 1
|
2天前
|
存储 数据可视化 索引
Python 金融编程第二版(三)(3)
Python 金融编程第二版(三)
11 1

相关实验场景

更多