我有一个包含类别的列的数据集。我想将某些类别合并到现有类别中。我试图通过将战争结合成行动、历史结合成纪录片、科幻结合成奇幻等,总共有 11 个类别
这是专栏信息:
df.genre.value_counts()
Drama 9081
Comedy 6562
Action 3692
Horror 2087
Crime 1435
Documentary 1334
Thriller 1312
Adventure 1301
Romance 931
Animation 830
Fantasy 573
Science Fiction 502
Mystery 457
Family 395
Western 375
Music 324
War 308
TV Movie 245
History 216
Foreign 60
Name: genre, dtype: int64
为了尝试结合历史和纪录片等值,我以前使用过
loc
函数但不记得正确的代码并不断出错。
我使用的代码(不正确):
df.loc[df.genre["History"].value_counts().reset_index() = df.genre["Documentary"]] = "Documentary"
df.loc[df.genre["War"].value_counts().reset_index() = df.genre["Action"]] = "Action"
最简单的建立地图然后使用
df.col.replace()
,见下文。
df_map = pd.DataFrame(dict(genre=['War','Adventure','Action'], genre_update=['Action','Action','Action']))
df_genre = pd.DataFrame(dict(genre=['War','Adventure','Action','Mystery'], val=[1,2,3,4]))
df_genre['updated'] = df_genre.genre.replace(dict(zip(df_map.genre, df_map.genre_update)))
| | genre | val | updated |
|---:|:----------|------:|:----------|
| 0 | War | 1 | Action |
| 1 | Adventure | 2 | Action |
| 2 | Action | 3 | Action |
| 3 | Mystery | 4 | Mystery |
注意,您可以使用
df.col.map()
但这会将未映射的值替换为 NaN。
df_genre['updated'] = df_genre.genre.map(dict(zip(df_map.genre, df_map.genre_update)))
| | genre | val | updated |
|---:|:----------|------:|:----------|
| 0 | War | 1 | Action |
| 1 | Adventure | 2 | Action |
| 2 | Action | 3 | Action |
| 3 | Mystery | 4 | nan |