python - Pandas:按行从 DataFrame 的特定列中选择值

标签 python pandas numpy indexing

给定一个包含多列的 DataFrame,我们如何从特定列中逐行选择值来创建一个新的 Series?

df = pd.DataFrame({"A":[1,2,3,4], 
                   "B":[10,20,30,40], 
                   "C":[100,200,300,400]})
columns_to_select = ["B", "A", "A", "C"]

目标: [10, 2, 3, 400]

一种有效的方法是使用 apply 语句。

df["cols"] = columns_to_select
df.apply(lambda x: x[x.cols], axis=1)

不幸的是,这不是矢量化操作,并且在大型数据集上需要很长时间。任何想法将不胜感激。

最佳答案

Pandas approach :

In [22]: df['new'] = df.lookup(df.index, columns_to_select)

In [23]: df
Out[23]:
   A   B    C  new
0  1  10  100   10
1  2  20  200    2
2  3  30  300    3
3  4  40  400  400

关于python - Pandas:按行从 DataFrame 的特定列中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997566/

相关文章:

python - 难以从理解中获取关键值(value)

python - 如何根据特定列表计算频率?

python - 检查某列的值是否位于 pandas 数据框中的另一个列数组中

python - 将低维 numpy 数组的部分提取到高维数组的最终轴中

python - Pandas:迭代 df 中的排序行,实现计数器

python - Mayavi 中的多图

python - 在 Python 中 - 如何在没有输出的情况下执行系统命令

python-3.x - 如何有效地在矩阵中获得一种 "maximum"

python - 具有多个参数的 R 扫描的高效 python pandas 等效/实现

带有参数列表的python函数