繁体   English   中英

如何用除某些值之外的字符串替换 Pandas 列的字符串值?

[英]How to replace string values of a Pandas column with a string except some values?

示例 DataFrame:

import pandas as pd
df = pd.DataFrame({'Age' : [70.0, 58.0, 44.0, 40.0, 21.0, 35.0, 12.0, 43.0, 45.0, 65.0, 56.0, 31.0, 30.0,
                            52.0, 59.0, 52.0, 31.0, 55.0, 42.0, 73.0],
                   'MarketSegment' : ['Travel Agent/Operator', 'Other', 'Other', 'Other', 'Other',
                                      'Direct', 'Groups', 'Other', 'Other', 'Direct', 'Other',
                                      'Other', 'Other', 'Other', 'Groups', 'Groups', 'Other', 'Other',
                                      'Groups', 'Other'],
                   'Nationality' : ['CAN', 'ESP', 'FRA', 'DEU', 'GBR', 'RUS', 'IRL', 'FRA', 'IRL',
                                    'BRA', 'LTU', 'CHE', 'FRA', 'GBR', 'FRA', 'PRT', 'DEU', 'ESP',
                                    'CHE', 'USA']})

首先,我只想要前 3 个最常见的国籍。 我使用了下面的代码:

top_nat = df.groupby('Nationality').count().sort_values \
(by='Age', ascending = False).head(3).iloc[:, 0].index.to_list()

(有没有办法只使用“民族”列中唯一值的频率来做到这一点?不使用任何其他列,比如“年龄”?)

现在我希望“民族”中的所有值都替换为“OTR”,除了值 == top_nat 中的值。 我试过这样的东西:

df['Nationality'].replace(~top_nat,'OTR', inplace=True)

df["Nationality"] = df["Nationality"].apply(lambda x: x.replace(~top_nat, "OTR"))

for x in top_nat:
    df.loc[df['Nationality'] != x, 'Nationality'] = 'OTR'

没有任何工作。 也许我想要类似的东西:

if values in df.Nationality != values in top_nat:
    replace that value in df.Nationality with 'OTR'
else:
    continue

原始数据集的形状是 (82580, 30),我需要前 15 个国籍。 请帮忙。

首先获得前3名:

top = df['Nationality'].value_counts().nlargest(3).index

然后设置国籍

df.loc[~df['Nationality'].isin(top), 'Nationality'] = 'OTR'

这将保留前 3 个国籍,并将其他所有内容替换为“OTR”

对于第一个问题,只需输入df['Nationality'].value_counts()[:3].index 您不需要在这里使用groupby()

对于第二个,您可以这样做:

a = list(df['Nationality'].value_counts()[:3].index)
df['Nationality'] = df['Nationality'].apply(lambda x : x if x not in a else 'OTR')

暂无
暂无

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

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