gpt4 book ai didi

python - 来自 If-Then-Else 语句的 Pandas 系列

转载 作者:太空宇宙 更新时间:2023-11-04 00:33:31 24 4
gpt4 key购买 nike

使用 if-then-else 语句(或类似语句)生成 Pandas 系列的最惯用方法是什么?

我有一组困惑的数据,其结构如下:

df = pd.DataFrame({
"label": ["a","b","a","b","a","b"],
"name": ["normal","normal","normal","special","normal","special"],
"value": [1,2,3,4,5,6]
})

我试图通过在字典中查找 label 的值来创建一个新标签,但如果 name 值为 "特别”。

我能够使用 df.apply 进行操作:

mapping = {"a": "apple", "b": "banana"}

df["new_label"] = df.apply(
lambda x:"pear" if x['name'] == "special" else mapping[x['label']],
axis=1
)

但是,apply 在运行大约 60k 行数据时已经减慢了我的程序,我期待更多。是否有更惯用和矢量化的方式来执行此类操作?

最佳答案

使用numpy.wheremap :

df["new_label"] = np.where(df['name'] == "special", 'pear', df['label'].map(mapping))

print (df)
label name value new_label
0 a normal 1 apple
1 b normal 2 banana
2 a normal 3 apple
3 b special 4 pear
4 a normal 5 apple
5 b special 6 pear

关于python - 来自 If-Then-Else 语句的 Pandas 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037179/

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