python - pandas 系列中的矢量化索引 numpy 数组与 pandas 系列中的布尔 numpy 数组
问题描述
以下可重现的代码生成了一个示例数据集,该数据集在更小范围内模拟了我的数据。
import numpy as np
import pandas as pd
np.random.seed(142536)
df = pd.DataFrame({
"vals": list(np.arange(12).reshape(3,4)),
"idx" : list(np.random.choice([True, False], 12).reshape(3,4))})
df
idx vals
0 [False, True, True, False] [0, 1, 2, 3]
1 [True, True, False, True] [4, 5, 6, 7]
2 [False, True, False, False] [8, 9, 10, 11]
以下可重现的代码返回我想要的结果,但对于大型数据集来说效率非常低。
我将如何更有效地做到这一点?
sel = []
for i in range(len(df.vals)):
sel.append(df.vals[i][df.idx[i]])
df['sel'] = sel
df
idx vals sel
0 [False, True, True, False] [0, 1, 2, 3] [1, 2]
1 [True, True, False, True] [4, 5, 6, 7] [4, 5, 7]
2 [False, True, False, False] [8, 9, 10, 11] [9]
我已经尝试过np.apply_along_axis()
、np.where()
、df.apply()
和df.transform()
,但无法让它们中的任何一个在没有错误的情况下为这种情况工作。
解决方案
前提很糟糕,因为您不应该像这样存储数据。您至少可以通过使用 连接数据itertools.chain
、索引,然后使用 拆分结果来加快速度np.array_split
。
from itertools import chain
fn = lambda x: np.array(list(chain.from_iterable(x)))
df['sel'] = np.array_split(
fn(df.vals)[fn(df.idx)], np.cumsum([sum(x) for x in df.idx][:-1]))
idx vals sel
0 [True, False, True, False] [0, 1, 2, 3] [0, 2]
1 [False, False, False, True] [4, 5, 6, 7] [7]
2 [False, True, True, False] [8, 9, 10, 11] [9, 10]
推荐阅读
- apache-camel - Apache Camel - 并行路由机上交换
- javascript - Angular 6 - 多次按下后退按钮触发
- ckeditor4.x - 在 CKeditor 4 上安装 SourceDialog 插件
- java - 用于在 JAVA 类中初始化对象值的 SOAP XML 请求
- ios - AVCaptureVideoPreviewLayer 在 iOS 中添加叠加层和捕捉照片
- c - MBEDTLS 是否有错误查找功能?
- batch-file - 在 Bat.File 中模拟 Enter
- windows - 阻止用户在 Windows 操作系统中执行可执行文件
- android - Android:在 Pie 和 Oreo 版本上显示键盘时显示白色视图
- node.js - Nestjs 中的请求提供程序,我无法导入 REQUEST 对象