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

Python - pandas 데이터 프레임을 CSV 파일에 쓰는 방법

<시간/>

Python에서 pandas 데이터 프레임을 CSV 파일에 쓰려면 to_csv()를 사용하세요. 방법. 먼저 목록 사전을 만들어 보겠습니다. −

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']
}

이제 위의 목록 사전에서 pandas 데이터 프레임을 만듭니다. -

dataFrame = pd.DataFrame(d)

아래에 바탕 화면 경로를 설정했기 때문에 출력 CSV 파일이 바탕 화면에 생성됩니다 -

dataFrame.to_csv("C:\\Users\\amit_\\Desktop\\sales1.csv\\SalesRecords.csv")

다음은 코드입니다 -

import pandas as pd

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']
}

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print("DataFrame...\n",dataFrame)

# write dataFrame to SalesRecords CSV file
dataFrame.to_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

# display the contents of the output csv
print("The output csv file written successfully and generated...")

출력

이것은 다음과 같은 출력을 생성합니다 -

DataFrame...
        Car   Date_of_purchase
0       BMW         2020-10-10
1     Lexus         2020-10-12
2      Audi         2020-10-17
3  Mercedes         2020-10-16
4    Jaguar         2020-10-19
5   Bentley         2020-10-22
The output csv file written successfully and generated...

결과 "SalesRecords.csv"는 다음 레코드, 즉 pandas 데이터 프레임으로 성공적으로 생성되었습니다. -

Python - pandas 데이터 프레임을 CSV 파일에 쓰는 방법