繁体   English   中英

Python Pandas 用“其他”替换列中的新值

[英]Python Pandas replace new values in column with 'other'

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

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

知道是什么原因造成的吗?

通过将值注入df1['column1'] df2['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)

暂无
暂无

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

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