본문 바로가기
개발일지/Pandas

pandas 판다스 틀린부분 복기3

by 개발에정착하고싶다 2022. 7. 19.
320x100

이번 문제 자체는 짧았지만,

정말 중요한 부분이였다.

하지만 머리에 잘 남지 않아서 아쉬움이 남은 파트였다.

더 익숙해져 보도록 하자.

 

# run the cell!
import pandas as pd
cars = pd.read_csv("cars.csv")
cars

'''
	mpg	cylinders	displacement	horsepower	weight	acceleration	model_year	origin	name
0	18.0	8	307.0	130.0	3504	12.0	70	usa	chevrolet chevelle malibu
1	15.0	8	350.0	165.0	3693	11.5	70	usa	buick skylark 320
2	18.0	8	318.0	150.0	3436	11.0	70	usa	plymouth satellite
3	16.0	8	304.0	150.0	3433	12.0	70	usa	amc rebel sst
4	17.0	8	302.0	140.0	3449	10.5	70	usa	ford torino
...	...	...	...	...	...	...	...	...	...
393	27.0	4	140.0	86.0	2790	15.6	82	usa	ford mustang gl
394	44.0	4	97.0	52.0	2130	24.6	82	europe	vw pickup
395	32.0	4	135.0	84.0	2295	11.6	82	usa	dodge rampage
396	28.0	4	120.0	79.0	2625	18.6	82	usa	ford ranger
397	31.0	4	119.0	82.0	2720	19.4	82	usa	chevrolet s-10
398 rows × 9 columns
'''
# 문제1
# Create a subset of the DataFrame cars with all cars having an mpg higher than 40! Save the subset in the variable high_eff!
# high_eff should be a new and independent DataFrame. Any changes in high_eff shall not influence the original DataFrame cars!

# 이 부분은 메모가 있었기에 맞출 수 있었다. 
# high_eff = cars.loc['mpg' > 40] 라고 했어서 에러가 났었다.
# high_eff = cars[cars.mpg > 40]

# 여기서 부터 잘못되었다. independent가 '독립적인'이라는 뜻으로써 copy()를 했어야 했는데, 단어의 뜻을 몰랐었다.
# high_eff = cars.loc[cars.mpg > 40].copy()
high_eff = cars.loc[cars.mpg > 40]
# 문제 2
# Cap the mpg for all cars in high_eff to 40 (Overwrite the mpg values)! Your code should not cause any warning message!

# 이것도 메모가 있었기에 맞출 수 있었고
# 실행 결과가 바로 작동 하였지만, 경고 메세지가 떴다.
# high_eff['mpg'] = 40
high_eff.mpg = 40

# 정답 코드는 에러메세지가 뜨지 않았다.

# copy()를 배제하고 변수 재설정을 해주었더니, 마찬가지로 경고가 뜬다.
# 문제3
# Check in the original cars Dataframe, whether there are still values greater than 40 in the "mpg" column!
# If so, your code is correct!

# run the cell!
cars.mpg.max()

# 원본파일도 함께 변해야하는데, 변수에 대해서는 변경이 되었지만
# 원본에 대해서는 함께 변경 실패했다.
# 정답코드도 'copy'를 썼을때, 당연한것일 수 있겠지만 원본에 변화가 없었다.

# 두번째로 돌릴때는 독립적이지 않은, 즉, copy가 아닌 변수로 지정해서 시도해보았다.
# 그래도 여전히 원본파일엔 영향이 없다.

# 46.6
# 문제4
# Now, we want to manipulate the original DataFrame cars. Cap all mpg values greater than 40 to 40! Your code should not cause any warning message!

cars.loc[cars.mpg > 40, 'mpg'] =40

# 체인인덱스 버전은
# cars.loc[cars.mpg > 40].mpg = 40
# 으로써, 이렇게 실행하면, 값에 변화가 없다.
# 문제 5
# Check, whether there are any values greater than 40 in the "mpg" column of the cars DataFrame. If so, your code was incorrect!

cars.mpg.max()

# 40.0

 

전체적으로 굉장히 짧막했다는 느낌이였다.

하지만 분명히 중요했다. 특히 체인 인덱싱에 대한 개념이 올바르지 않지만, 결과적으로는

쓰면 안좋다 정도는 알고있다.

경고도 무조건적으로 나쁜건 아니지만, 가급적이면 없이 진행되는 코드로 되는게 좋구.

 

아직 갈길이 멀다.

300x250