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

Làm thế nào để sắp xếp một loạt Gấu trúc?

Trong bài toán này, chúng ta phải sắp xếp một chuỗi Pandas. Chúng tôi sẽ xác định một chuỗi gấu trúc không được sắp xếp và sẽ sắp xếp nó bằng cách sử dụng hàm sort_values ​​() trong thư viện Pandas.

Thuật toán

Step 1: Define Pandas series.
Step 2: Sort the series using sort_values() function.
Step 3: Print the sorted series.

Mã mẫu

import pandas as pd

panda_series = pd.Series([18,15,66,92,55,989])
print("Unsorted Pandas Series: \n", panda_series)

panda_series_sorted = panda_series.sort_values(ascending = True)
print("\nSorted Pandas Series: \n", panda_series_sorted)

Đầu ra

Unsorted Pandas Series:
0     18
1     15
2     66
3     92
4     55
5    989
dtype: int64

Sorted Pandas Series:
1     15
0     18
4     55
2     66
3     92
5    989
dtype: int64

Giải thích

Tham số tăng dần trong hàm sort_values ​​() nhận giá trị boolean. Nếu giá trị là True, nó sẽ sắp xếp chuỗi theo thứ tự tăng dần. Nếu giá trị là Sai, nó sẽ sắp xếp giá trị theo thứ tự giảm dần.