首页 > 解决方案 > 如何制作一个包含每个单词的新数据框并使用另一列进行计数

问题描述

让我解释。我的df样子是这样的:

id `  text                             c1      
1     Hello world how are you people    1 
2     Hello people I am fine  people    1
3     Good Morning people               -1
4     Good Evening                      -1

c1仅包含两个值 1 或 -1

现在我想要一个这样的数据框(输出):

Word      Totalcount     Points      PercentageOfPointAndTotalCount

hello        2             2              100
world        1             1              100
how          1             1              100
are          1             1              100
you          1             1              100
people       3             1              33.33
I            1             1              100
am           1             1              100
fine         1             1              100
Good         2             -2            -100
Morning      1             -1            -100
Evening      1             -1            -100

这里,是每个单词在列中Totalcount出现的总次数。text

pointsc1每个单词的总和。示例:people单词在两行中c1是 1,在一行中c1是1 -1。所以重点是 1 (2-1 = 1)。

PercentageOfPointAndTotalCount = 点数/TotalCount*100

print(df)

      id comment_text  target
0  59848  Hello world    -1.0
1  59849  Hello world    -1.0

标签: pythonpandas

解决方案


之后我使用取消嵌套str.split,,我们只需要groupby+agg

unnesting(df,['text']).groupby('text').c1.agg(['count','sum'])
Out[873]: 
         count  sum
text               
Evening      1   -1
Good         2   -2
Hello        2    2
I            1    1
Morning      1   -1
am           1    1
are          1    1
fine         1    1
how          1    1
people       4    2
world        1    1
you          1    1

def unnesting(df, explode):
    idx = df.index.repeat(df[explode[0]].str.len())
    df1 = pd.concat([
        pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
    df1.index = idx

    return df1.join(df.drop(explode, 1), how='left')

推荐阅读