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

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

问题描述

我有一个 Pandas 数据框 df,如下图所示:

品牌专长高乙美国广播公司DKAB

我想用 A 替换 BrandName 列中的ABC"和AB".有人可以帮忙吗?

解决方案

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

<预><代码>>>>df['品牌'].replace(['ABC', 'AB'], 'A')0 安1 乙2A3D4A

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

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

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?

解决方案

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天全站免登陆