Pandas的valuecounts函數排序

從 YTYZX有图有真相的百科
於 2022年8月26日 (五) 17:48 由 Ytyzx (對話 | 貢獻) 所做的修訂
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
跳到: 導覽搜尋
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