繁体   English   中英

如何替换熊猫数据框中的多个值?

[英]How to replace multiple values in a pandas dataframe?

如何在Pandas DataFrame中使用映射替换多个值?

我有一列要替换为以下映射。

mapping
apple=fruit
tomato=vegetable
steak=protein
milk=dairy

这样我的专栏就变成了。

col1       ->     col1
apple             fruit
apple             fruit
tomato            vegtable
steak             protein
milk              dairy

我怎样才能最有效地做到这一点?

只需使用您的映射创建一个字典,然后调用Series.map

>>> d = {'apple': 'fruit', 
         'tomato': 'vegetable', 
         'steak': 'protein', 
         'milk': 'dairy'}

>>> df.col1.map(d)

0        fruit
1        fruit
2    vegetable
3      protein
4        dairy
Name: col1, dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM