如何在Pandas DataFrame中对值进行分类

1 投票
3 回答
50 浏览
提问于 2025-04-14 18:15

我有一个数据框,内容如下:

城市_公司 主题
伦敦 医疗保健
西雅图 创业
哥本哈根 工程
墨尔本 法律
山景城 b
布里斯班 c
旧金山 d

这里有很多主题的分类。我想把b、c、d这些名称都改成“其他”。(当然,不仅仅是b、c、d,还有很多其他的值。)我只想保留这些值:["医疗保健", "创业", "工程", "法律", "其他"]。如果有其他不同的值,就都改成“其他”。

城市_公司 主题
伦敦 医疗保健
西雅图 创业
哥本哈根 工程
墨尔本 法律
山景城 其他
布里斯班 其他
旧金山 其他

3 个回答

0

你可以使用pandas库中的apply方法来转换"Subject"这一列的数据。

df["Subject"] = df["Subject"].apply(lambda subject:"Other" if subject not in ["Health Care", "Entrepreneurship", "Engineering", "Law"] else subject)
0

你可以使用 numpy.where 这个功能:

valid_subjects = ["Health Care", "Entrepreneurship", "Engineering", "Law"]
df["Subject"] = np.where(df["Subject"].isin(valid_subjects), df["Subject"], "Other")
    city_company           Subject
0         London       Health Care
1        Seattle  Entrepreneurship
2     Copenhagen       Engineering
3      Melbourne               Law
4  Mountain View             Other
5       Brisbane             Other
6  San Francisco             Other
1

你可以检查一下需要的值,然后把它们替换掉。

import pandas as pd                                                                                                         
dd = {"city_company": ["London", "Seattle", "Copenhagen", "Melbourne", "Mountain View", "Brisbane", "San Francisco"],       
                                                                                                                            
"Subject": ["Health Care", "Entrepreneurship", "Engineering", "Law", "b", "c", "d"]                                         
                                                                                                                            
}                                                                                                                           
df = pd.DataFrame(dd)                                                                                                                                                                          
df.loc[~df['Subject'].isin( ["Health Care", "Entrepreneurship", "Engineering", "Law", "Other"]), ["Subject"]] = "Other"                                                                            

撰写回答