我有一个带有混合分类类别的单词表。我要这样做,以使“公共类型”列具有最高的出现(模式)分类标签,以便每一行都有一个标签。
word type common type
post | WORK_OF_ART | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | OTHER | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | WORK_OF_ART | WORK_OF_ART
post | OTHER | WORK_OF_ART
-----|--------------------------
sign | OTHER | OTHER
sign | WORK_OF_ART | OTHER
sign | OTHER | OTHER
sign | WORK_OF_ART | OTHER
sign | OTHER | OTHER
sign | OTHER | OTHER
sign | WORK_OF_ART | OTHER
我具有以下功能,但在1m +行的数据帧上,运行时很糟糕
def replace_most_common_type(frame, word):
common_type = frame[frame['word']==word]['type'].value_counts().idxmax()
frame.loc[frame['word']==word, 'type'] = common_type
unique_words = master_frame['word'].unique()
for idx, word in unique_words:
replace_most_common_type(master_frame, word)
内置的pandas方法通常会被numpy向量化,因此赞赏使用本机pandas函数的任何解决方案
提供您的数据:
In [1]: df
Out[1]:
word type
0 post WORK_OF_ART
1 post WORK_OF_ART
2 post WORK_OF_ART
3 post WORK_OF_ART
4 post WORK_OF_ART
5 post OTHER
6 post WORK_OF_ART
7 post WORK_OF_ART
8 post OTHER
9 sign OTHER
10 sign WORK_OF_ART
11 sign OTHER
12 sign WORK_OF_ART
13 sign OTHER
14 sign OTHER
15 sign WORK_OF_ART
您可以按单词分组,然后使用value_counts
查找每个单词的最常见类型,如this answer所示。请注意,您可以将“最常见的”系列保存到变量中,然后重命名它,以使您的列名不会冲突。
In [2]: s = df.groupby('word')['type'].agg(lambda x: x.value_counts().index[0])
...: s.name = 'common type'
...: df.merge(s, on='word')
Out[2]:
word type common type
0 post WORK_OF_ART WORK_OF_ART
1 post WORK_OF_ART WORK_OF_ART
2 post WORK_OF_ART WORK_OF_ART
3 post WORK_OF_ART WORK_OF_ART
4 post WORK_OF_ART WORK_OF_ART
5 post OTHER WORK_OF_ART
6 post WORK_OF_ART WORK_OF_ART
7 post WORK_OF_ART WORK_OF_ART
8 post OTHER WORK_OF_ART
9 sign OTHER OTHER
10 sign WORK_OF_ART OTHER
11 sign OTHER OTHER
12 sign WORK_OF_ART OTHER
13 sign OTHER OTHER
14 sign OTHER OTHER
15 sign WORK_OF_ART OTHER