python - 如何在 Pandas 中矢量化动态大小的 numpy 数组

标签 python pandas numpy dataframe apply

目前,我正在使用 apply方法来创建一个包含可变大小列表的计算列(取决于 length 列中的值)。
有没有办法使用 Pandas 更有效地创建具有可变大小列表的列?

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [
                  6, 7, 8, 9, 0], 'length': [3, 5, 7, 9, 3]})
df['computed'] = df.apply(
    lambda x: np.array([x['a'], x['b']] + [x['b'] + i for i in range(1, x['length'] - 1)]), axis=1)
所需的输出(适用于上面的代码,但速度较慢):
   a  b  length                            computed
0  1  6       3                           [1, 6, 7]
1  2  7       5                    [2, 7, 8, 9, 10]
2  3  8       7           [3, 8, 9, 10, 11, 12, 13]
3  4  9       9  [4, 9, 10, 11, 12, 13, 14, 15, 16]
4  5  0       3                           [5, 0, 1]

最佳答案

尝试这个,

df['computed']= [[a]+[b]+list(np.arange(b+1, length)) for a, b, length in zip(df.a, df.b, (df.b) + df.length-1)]
开/关:
   a  b  length                            computed
0  1  6       3                           [1, 6, 7]
1  2  7       5                    [2, 7, 8, 9, 10]
2  3  8       7           [3, 8, 9, 10, 11, 12, 13]
3  4  9       9  [4, 9, 10, 11, 12, 13, 14, 15, 16]
4  5  0       3                           [5, 0, 1]

关于python - 如何在 Pandas 中矢量化动态大小的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63742177/

相关文章:

python - 在 HTML 按钮中引用 Django URL

python - 在 jupyter notebook python 中密谋

python - Pandas 列创建方法

python - pandas.DataFrame.shift() fill_value 不工作

python - numpy:将(an,)数组转换为(n,1)数组的语法/习惯用法?

python - 将列中的文本拆分为多行,每行包含相同数量的单词

python - SQLAlchemy 截断列=(整数)

numpy - 在散点图中将值绘制为符号的最简单方法?

python - 使用 pygtk 绘制 2d numpy 像素数据数组的最快方法是什么?

python - python 的 ORM 库 peewee 中与foreignkeyfield对象一起使用的 "related_name"属性是什么?