组中的稀有值后,对pandas数据框中的列进行排序

时间:2018-11-12 15:17:00

标签: python pandas

我有一个抓取网站的pandas数据框,其中包含网站标识符,网站的文字和标签。少数网站有两个标签,但是由于我想首先训练一个标签分类器,因此我想为每个网站创建一个只有一个标签的数据版本(我知道这有点麻烦)。我的数据集中的标签不平衡(有些标签经常出现,有些很少出现)。如果我删除重复的网站ID,我想删除最常见的标签。这就是我带有多个标签的数据集的样子:

ID   Label   Text
1    a       some text
1    b       other text
1    a       data
2    a       words
2    c       more words
3    a       text
3    b       short text

我的想法是按照标签的稀有性对每个网站标识符中的标签列进行排序。为此,我首先在label列上进行value_counts(ascending = True),以获取按稀有度排序的所有标签的列表。

to_sort = [c, b, a]

然后,我想使用该列表按稀有性对每个网站ID进行排序。不过,我不确定该怎么做。结果应如下所示:

ID   Label   Text
1    b       other text
1    a       some text
1    a       data
2    c       more words
2    a       words
3    b       short text
3    a       text

然后我将使用df.drop_duplicates(subset = 'ID', keep = 'first')来保留最稀有的标签。如何进行排序?

2 个答案:

答案 0 :(得分:0)

使用有序的categorical,因此可以使用sort_values

to_sort = list('cba')

df['Label'] = pd.Categorical(df['Label'], ordered=True, categories=to_sort)

df = df.sort_values(['ID','Label'])
print (df)
   ID Label        Text
1   1     b  other text
0   1     a   some text
2   1     a        data
4   2     c  more words
3   2     a       words
6   3     b  short text
5   3     a        text

答案 1 :(得分:0)

您可以通过将标签列设置为类别,然后按 ID Label 进行排序来实现目标。让我们在实践中看一下。

import pandas as pd
df = pd.DataFrame( {'ID': [1,1,1,2,2,3,3], "Label": ["a", "b", "a", "a", "c", "a", "b"],
                   'Text': ["some text", "other text","data", "words", "more words", "text", "short text"]} )
df
    ID  Label   Text
0   1   a   some text
1   1   b   other text
2   1   a   data
3   2   a   words
4   2   c   more words
5   3   a   text
6   3   b   short text

通过以下步骤定义标签的顺序:

to_sort = df.Label.value_counts(ascending = True).index
to_sort
Index(['c', 'b', 'a'], dtype='object')

然后将标签列设为类别

df.Label = pd.Categorical(df.Label,categories = to_sort, ordered = True)

最后,按 ID 标签进行排序:

df.sort_values(["ID", "Label"]).reset_index(drop = True)

    ID  Label   Text
0   1   b   other text
1   1   a   some text
2   1   a   data
3   2   c   more words
4   2   a   words
5   3   b   short text
6   3   a   text