简体   繁体   English

用另一个值替换熊猫数据框列中的几个值

[英]Replacing few values in a pandas dataframe column with another value

I have a pandas dataframe df as illustrated below:我有一个熊猫数据框 df 如下图所示:

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?我想用 A 替换 BrandName 列中的“ABC”和“AB”。有人可以帮忙吗?

The easiest way is to use the replace method on the column.最简单的方法是在列上使用replace方法。 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):参数是您要替换的内容的列表(此处为['ABC', 'AB'] )以及要替换的内容(在本例中为字符串'A' ):

>>> 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')

Replace代替

DataFrame object has powerful and flexible replace method: DataFrame对象具有强大而灵活的replace方法:

DataFrame.replace(
        to_replace=None,
        value=None,
        inplace=False,
        limit=None,
        regex=False, 
        method='pad',
        axis=None)

Note, if you need to make changes in place, use inplace boolean argument for replace method:请注意,如果您需要inplace进行更改,请使用inplace布尔参数replace方法:

Inplace到位

inplace : boolean, default False If True , in place.就地:布尔值,默认为False如果True ,就地。 Note: this will modify any other views on this object (eg a column form a DataFrame).注意:这将修改此对象上的任何其他视图(例如,DataFrame 中的列)。 Returns the caller if this is True .如果这是True则返回调用者。

Snippet片段

df['BrandName'].replace(
    to_replace=['ABC', 'AB'],
    value='A',
    inplace=True
)

loc方法可用于替换多个值:

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

You could also pass a dict to the pandas.replace method:您还可以将dict传递给pandas.replace方法:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this'
    }
})

This has the advantage that you can replace multiple values in multiple columns at once, like so:这样做的好处是您可以一次替换多列中的多个值,如下所示:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this',
        'foo': 'bar',
        'spam': 'eggs'
    },
    'other_column_name': {
        'other_value_to_replace': 'other_replace_value_with_this'
    },
    ...
})

This solution will change the existing dataframe itself:此解决方案将更改现有数据帧本身:

mydf = pd.DataFrame({"BrandName":["A", "B", "ABC", "D", "AB"], "Speciality":["H", "I", "J", "K", "L"]})
mydf["BrandName"].replace(["ABC", "AB"], "A", inplace=True)

Created the Data frame:创建数据框:

import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})

Now use DataFrame.replace() function:现在使用DataFrame.replace()函数:

dk.BrandName.replace(to_replace=['ABC','AB'],value='A')

Just wanted to show that there is no performance difference between the 2 main ways of doing it:只是想表明两种主要方法之间没有性能差异:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))

def loc():
    df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


def replace():
    df2['A'].replace(
        to_replace=2,
        value=5,
        inplace=True
    )
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

You can use loc for replacing based on condition and specifying the column name您可以使用 loc 根据条件进行替换并指定列名

df = pd.DataFrame([['A','H'],['B','I'],['ABC','ABC'],['D','K'],['AB','L']],columns=['BrandName','Col2'])
df.loc[df['BrandName'].isin(['ABC', 'AB']),'BrandName'] = 'A'

Output输出
在此处输入图片说明

暂无
暂无

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

相关问题 从另一个数据帧中的列值替换pandas数据帧中的列中的值 - Replacing value in a column in pandas dataframe from a column value in another dataframe 用另一列中的相同行值替换 pandas dataframe 列中的值 - Replacing values in pandas dataframe column with same row value from another column 根据另一列的值替换 Pandas dataframe 中的特定值 - Replacing specific values in a Pandas dataframe basing on the values of another column 替换 Pandas DataFrame 中的列值 - Replacing column values in a pandas DataFrame 用另一列中的值替换pandas列中的值 - Replacing pandas column value with values from another column 用 pandas dataframe 中同一列上的不同值替换缺失值 - replacing the missing value with different values on the same column in pandas dataframe 用另一个列值的子字符串替换 dataframe 的 null 值 - Replacing null values of a dataframe with a sub-string of another column value 根据另一个 Pandas DataFrame 中的值替换 Pandas DataFrame 中的缺失值 - Replacing missing values in a Pandas DataFrame based on values in another Pandas DataFrame Pandas:将从 DataFrame 中提取的值乘以另一个 DataFrame 中的列值 - Pandas: Multiplying a value extracted from a DataFrame to column values in another DataFrame 通过将一列中的 NaN 值替换为另一列中的非 NaN 值来更新 Pandas dataframe - Updating a Pandas dataframe by replacing NaN values in a column with not NaN values from another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM