IT/가짜연구소 스터디

[DA]4-2. Importing Data From Excel Files

Millennials 2022. 9. 13. 17:27
해당 내용은 Datacamp의 Data engineering track을 정리했습니다.
4. Streamlined Data Ingestion with pandas의 chapter 2에 대한 내용입니다.

# 1. Introduction to spreadsheets

마이크로소프트의 Excel 프로그램은 아주 잘 알려진 소프트웨어이고, Excel file은 데이터를 다룰때 흔히 볼 수 있는 양식입니다.

판다스에서는 pd.read_excel() 함수를 통해 Excel형식의 파일을 읽어 올 수 있습니다.

read_excel 또한 read_csv()와 같이 많은 argument들을 공유합니다.

- nrows : 불러올 행의 숫자를 제한합니다.

- skiprows : 행을 건너띄고 불러옵니다.

- usecols : 불러올 열을 지정합니다.

 

## 1.1 Get data from a spreadsheet

## 1.2 Load a portion of a spreadsheet

# 2. Getting data from multiple worksheets

Excel에 여러 시트의 데이터를 가져오는 방법을 알아봅시다.

시트는 sheet_name의 argument를 추가하면서 가져올 수 있습니다.

여러개의 sheet를 동시에 가져오는 경우 Dict형태로 가지고 오게 됩니다. key에는 sheet_name이, value에는 Dataframe이 오게 됩니다.

# Create empty dataframe
all_responses = pd.DataFrame()

# Iterate
for sheet_name, frame in survey_responses.items():
	frame['Year'] = sheet_name
    
    # Add each dataframe to all_responses
    all_responses = all_responses.append(frame)
   
print(all_responses.Year.unique())

## 2.1 Select a single sheet

## 2.2 Select multiple sheets

# 3. Modifying imports: true/false data

 

Boolean 데이터 타입을 통해 필터링을 할 수 있습니다.

Pandas에서는 dtype으로 Boolean 타입이 포함되어 있지 않습니다. 

판다스에서 True는 1으로 False는 0으로 인식합니다.

- null 값은 isna()를 사용해서 찾을 수 있습니다.

- dtype={"대상 column":bool} 형식을 통해 boolean 타입으로 변환할 수 있습니다.

- true_values 와 false_values argument를 통해 각각 true값과 false 값을 변경할 수 있습니다.

 

# Load file with Yes as a True value and No as a False value
survey_subset = pd.read_excel("fcc_survey_yn_data.xlsx",
                              dtype={"HasDebt": bool,
                              "AttendedBootCampYesNo": bool},
                              true_values=['Yes'],
                              false_values=['No'])

# View the data
print(survey_subset.head())

# 4. Modifying imports:parsing dates

이번에는 datetime을 만져보겠습니다.

datetime은 dtype argument가 아니라 parse_dates argument를 사용합니다.

이 parse_dates로 읽어오기 위해서는 pandas가 인식할 수 있게 표현된 datetime 데이터가 필요합니다.

만약 pandas가 인식하지 못하는 형태이라면 pd.to_datetime()으로 해당 데이터를 datetime 형식으로 바꾸어줄 필요가 있습니다.

# Create dict of columns to combine into new datetime column
datetime_cols = {"Part2Start": ["Part2StartDate","Part2StartTime"]}


# Load file, supplying the dict to parse_dates
survey_data = pd.read_excel("fcc_survey_dts.xlsx",
                            parse_dates=datetime_cols)

# View summary statistics about Part2Start
print(survey_data.Part2Start.describe())
# Parse datetimes and assign result back to Part2EndTime
survey_data["Part2EndTime"] = pd.to_datetime(survey_data["Part2EndTime"], 
                                             format="%m%d%Y %H:%M:%S")
반응형