用另一个值替换大 pandas 数据框列中的几个值 [英] Replacing few values in a pandas dataframe column with another value

查看:114
本文介绍了用另一个值替换大 pandas 数据框列中的几个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大熊猫数据框df,如下所示:

I have a pandas dataframe df as illustrated below:

BrandName Specialty
A          H
B          I
ABC        J
D          K
AB         L

我要替换'可以有人帮忙吗?

I want to replace 'ABC' and 'AB' in column BrandName by A. Can someone help with this?

推荐答案

最简单的方法是在列上使用替换方法。参数是要替换的内容的列表(这里 ['ABC','AB'] )以及要替换的内容(字符串'A'在这种情况下):

The easiest way is to use the replace method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']) and what you want to replace them with (the string 'A' in this case):

>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0    A
1    B
2    A
3    D
4    A

这将创建一系列新的值,因此您需要将此新列分配给正确的列名:

This creates a new Series of values so you need to assign this new column to the correct column name:

df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')

这篇关于用另一个值替换大 pandas 数据框列中的几个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆