【问题标题】:Adding a 'rest'-group with Pandas value_counts()使用 Pandas value_counts() 添加“休息”组
【发布时间】:2017-05-13 16:24:48
【问题描述】:

我刚开始使用 pandas 库来分析大型数据集。我正在分析具有属性issuercountrycode 的信用卡数据,其中包含 117 种可能性。在尝试可视化我的数据集中使用的 issuercountrycode 时,我目前使用以下代码生成饼图。

df['issuercountrycode'].value_counts().plot(kind='pie')
plt.show()

这会产生以下饼图:

如您所见,这并不理想,因为不经常使用多个值。 pandas 是否有可能在使用 value_counts() 函数时添加阈值,并将低于某个值的值添加到“休息”组?这些类型的操作在 pandas 中甚至是可能的吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您需要用boolean indexingsum 计算它:

    tresh = 2
    a = df['issuercountrycode'].value_counts()
    b = a[a > tresh]
    b['rest'] = a[a <= tresh].sum()
    

    示例:

    np.random.seed(10)
    L = list('abcdef')
    df = pd.DataFrame({'issuercountrycode':np.random.choice(L, size=15)})
    
    tresh = 2
    a = df['issuercountrycode'].value_counts()
    b = a[a > tresh]
    b['rest'] = a[a <= tresh].sum()
    print (b)
    b       5
    f       3
    a       3
    rest    4
    Name: issuercountrycode, dtype: int64
    
    b.plot.pie()
    

    【讨论】:

    • 很高兴能帮上忙,周末愉快!
    猜你喜欢
    • 2016-08-14
    • 2022-12-02
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多