Python Pandas 将列中的新值替换为 'other'



我有一个pandas数据框架,它的因子列有30个不同的级别。有些级别很少出现,所以我将它们转换为"其他"组。结果列有25个不同的级别加上1个'other'级别。

d = df1['column1'].value_counts() >= 50
df1['column1'] = [i if d[i] else 'Other' for i in df1['column1']]
df1['column1'] = df1['column1'].astype('category')

我有第二个数据帧,我想转换为具有与第一个数据帧相同的级别(包括没有出现在第一个数据帧中的任何新级别)。我试过下面的代码,但我得到一个'键错误',但它并没有真正解释这个问题。

df2['column1'] = [i if d[i] else 'Other' for i in df2['column1']]
df2['column1'] = df2['column1'].astype('category') 

知道是什么引起的吗?

我能够通过向df2['column1']中注入df1['column1']中不存在的值来复制您的Key Error

您可以通过以下操作使该过程具有弹性:

df1 = pd.DataFrame({'column1': [f'L{x}' for x in np.random.randint(10, size=100)]})

df2包含附加值:

df2 = pd.DataFrame({'column1': [f'L{x}' for x in np.random.randint(12, size=100)]})

获取最常见的级别并翻译:

cat_counts = df1['column1'].value_counts()
df1.assign(column1=np.where(df1['column1'].isin(cat_counts[cat_counts > 10].index), df1['column1'], 'other')).astype({'column1': 'category'})
column1
0       L4
1       L9
2       L9
3    other
4    other
..     ...
95   other
96   other
97   other
98      L3
99   other

同样的结构也适用于df2,即使它包含df1中不存在的值:

df2.assign(column1=np.where(df2['column1'].isin(cat_counts[cat_counts > 10].index), df2['column1'], 'other')).astype({'column1': 'category'})
column1
0    other
1       L9
2    other
3    other
4    other
..     ...
95   other
96   other
97   other
98      L9
99   other

另一个选项是选择n个最常见的级别:

df1['column1'].isin(cat_counts.nlargest(5).index)

最新更新