Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 단일 열로 CSV를 정렬하는 방법은 무엇입니까?

<시간/>

단일 열을 기준으로 CSV를 정렬하려면 sort_values() 메서드를 사용합니다. sort_values() 메서드에서 정렬할 열을 설정합니다.

먼저 DataFrame을 사용하여 CSV 파일 "SalesRecords.csv"를 읽어 보겠습니다. −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

단일 열 "자동차"에 따라 정렬 -

dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')

다음으로 단일 열 "Reg_Price"에 따라 정렬 -

dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')

예시

다음은 코드입니다.

import pandas as pd

# DataFrame to read our input CS file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nInput CSV file = \n", dataFrame)

# sorting according to Car column
dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')

print("\nSorted CSV file (according to Car Names) = \n", dataFrame)

# sorting according to Reg_Price column
dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')

print("\nSorted CSV file (according to Registration Price) = \n", dataFrame)

출력

그러면 다음과 같은 출력이 생성됩니다.

Input CSV file =
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1         Audi         10/12/2020         750
2        Lexus         10/17/2020        1250
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Sorted CSV file (according to Car Names) =
           Car   Date_of_Purchase   Reg_Price
1         Audi         10/12/2020         750
0          BMW         10/10/2020        1000
3       Jaguar         10/16/2020        1500
5  Lamborghini         10/22/2020        1000
2        Lexus         10/17/2020        1250
4      Mustang         10/19/2020        1100

Sorted CSV file (according to Registration Price) =
           Car   Date_of_Purchase   Reg_Price
1         Audi         10/12/2020         750
0          BMW         10/10/2020        1000
5  Lamborghini         10/22/2020        1000
4      Mustang         10/19/2020        1100
2        Lexus         10/17/2020        1250
3       Jaguar         10/16/2020        1500