【问题标题】:How to split text data and count number of occurrences in pandas dataframe?如何拆分文本数据并计算熊猫数据框中的出现次数?
【发布时间】:2018-06-06 13:43:46
【问题描述】:

我在数据框中有以下格式的数据:

df=pd.DataFrame([
    [42,{"tags":["illustration","logo","design","ui"]}],
    [81,{"tags":["typography","icon","vector","ux"]}],
    [98,{"tags":["branding","app"]}],
    [52,{"tags":["animation","web","flat"]}],
    [17,{"tags":["type","lettering"]}],
    [37,{"tags":["illustration","typography","branding","typography","branding"]}],
    [63,{"tags":["logo","icon","app","web","lettering"]}],
    [47,{"tags":["ui","ux"]}],
    [6,{"tags":["design","vector","icon","flat","lettering","branding","app"]}],
    [53,{"tags":["ui","ux","lettering","branding","app","animation","web","flat"]}],
    [64,{"tags":["branding","app","typography","branding"]}],
    [89,{"tags":["typography","branding","ux","lettering","branding"]}]
],columns=["_id","tags"])

我想用特定数量的标签计算“id”的数量(这个数字的分布),所以对于上面的数据,它会是:

Number of posts    Number of tags 
     3                 2
     1                 3
     3                 4 
     3                 5
     1                 7

我应该如何处理这个任务给定格式的文本标签?

谢谢

【问题讨论】:

    标签: pandas dataframe split


    【解决方案1】:

    使用DataFrame构造函数+Counterlist理解每个tags的计数长度为lists:

    from collections import Counter
    
    c = Counter([len(x['tags']) for x in df['tags']])
    
    df = pd.DataFrame({'Number of posts':list(c.values()), ' Number of tags ': list(c.keys())})
    print (df)
       Number of posts   Number of tags 
    0                3                 4
    1                3                 2
    2                1                 3
    3                3                 5
    4                1                 7
    5                1                 8
    

    或将applyvalue_counts 一起使用:

    df = (df['tags'].apply(lambda x: len(x['tags']))
                    .value_counts()
                    .rename_axis('Number of tags')
                    .reset_index(name='Number of posts')
                    [['Number of posts','Number of tags']])
    print (df)
       Number of posts  Number of tags
    0                3               5
    1                3               4
    2                3               2
    3                1               8
    4                1               7
    5                1               3
    

    【讨论】:

    • 谢谢。我刚刚注意到某些数据可能不是我指定的格式。数据可能包含也可能不包含一些其他信息。请在此处查看:pastebin.com/Pv4mXN8e 您能否告诉我在这种情况下如何更改代码?谢谢! @jezrael
    • 抱歉,我现在离线,只能在手机上使用。所以稍后尝试寻找解决方案。
    • 这样我就可以获得仅带有标签的数据框(就像在原始问题中一样)。当我运行这两种方法时,我得到相同的错误:TypeError:字符串索引必须是整数
    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2020-03-29
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多