Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Sắp xếp DataFrame theo thứ tự giảm dần theo tần suất phần tử

Để sắp xếp dữ liệu theo thứ tự tăng dần hoặc giảm dần, hãy sử dụng phương thức sort_values ​​(). Đối với thứ tự giảm dần, hãy sử dụng như sau trong phương thức sort_values ​​() -

ascending=False

Nhập thư viện bắt buộc -

import pandas as pd

Tạo DataFrame có 3 cột -

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)

Để sắp xếp DataFrame theo thứ tự giảm dần theo tần suất phần tử, chúng ta cần đếm số lần xuất hiện. Do đó, count () cũng được sử dụng với sort_values ​​() được đặt để sắp xếp thứ tự giảm dần -

dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)

Ví dụ

Sau đây là mã -

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)

print"DataFrame ...\n",dataFrame

# Sort DataFrame in descending order according to the element frequency
dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)

print"\nSorting DataFrame ...\n",dataFrame

Đầu ra

Điều này sẽ tạo ra kết quả sau -

DataFrame ...
         Car     Place   Reg_Price
0       BMW       Pune        7000
1     Lexus      Delhi        1500
2       BMW     Mumbai        5000
3   Mustang  Hyderabad        8000
4  Mercedes  Bangalore        9000
5     Lexus Chandigarh        2000

Sorting DataFrame ...
        Car   Count
0       BMW       2
1     Lexus       2
2  Mercedes       1
3   Mustang       1