gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:20:51 32 4
gpt4 key购买 nike

给定一个包含多列的 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com