使用 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.where
与 map
:
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
我是一名优秀的程序员,十分优秀!