Pandas的valuecounts函数排序

来自YTYZX有图有真相的百科
Ytyzx讨论 | 贡献2022年8月26日 (五) 17:48的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索
Python的pandas中,可以使用value_counts函数统计返回一个包含计数的Series,默认以值排序输出,可以在后面加上sort_index(),从而按照索引index输出。
1. 输入一下内容生成一个DataFrame.
        import pandas as pd
        ITDevices_record = pd.DataFrame({'Quantity': {0: 50, 1: 50, 2: 70,
                                3: 50, 4: 80, 5: 100,
                                6: 30, 7: 106},
                         'Product_Names': {0: 'Mosuse', 1: 'Keyboard',
                                  2: 'Headphones', 3: 'CPU',
                                  4: 'Flash Drives', 5: 'Tablets',
                                  6: 'Android Box', 7: 'LCD'},
                         'Product_Prices': {0: 100, 1: 70, 2: 150, 3: 1500,
                                   4: 70, 5: 1700, 6: 2500, 7: 1600},})
        print(ITDevices_record)

PandasValueCounts1.png

2.输入print(ITDevices_record['Quantity'].value_counts()),以值进行排序。
  Quantity等于50的计数为3,所以排在第一位。

PandasValueCounts2.png

3.输入print(ITDevices_record['Quantity'].value_counts(sort=False).sort_index()),以索引进行排序。
  按照Quantity的大小(Quantity为30的排在第一位)进行排序。

PandasValueCounts3.png