1. 표를 불러옵니다

import seaborn as sns              # seaborn패키지에는 유명한 데이터 몇가지 있어서 불러와봤습니다
planets = sns.load_dataset('planets')              # planets라는 데이터셋 부르기

 

2. 데이터/컬럼 수 확인

planets.shape 

출력>
(1035, 6)

 

3. 대략의 표 확인

planets.head() 

출력>
method	number	orbital_period	mass	distance	year
0	Radial Velocity	1	269.300	7.10	77.40	2006
1	Radial Velocity	1	874.774	2.21	56.95	2008
2	Radial Velocity	1	763.000	2.60	19.84	2011
3	Radial Velocity	1	326.030	19.40	110.62	2007
4	Radial Velocity	1	516.220	10.50	119.47	2009

 

4. 데이터 정제 : NaN 데이터 제거 (혹은 mean으로 평균값을 내주는 방법도 있다)

.dropna : NaN 값이 있는 행또는 열을 제거할 수 있다. 기본적으로 axis=0으로 세팅되어있다.

planets.dropna()

출력>

method	number	orbital_period	mass	distance	year
0	Radial Velocity	1	269.30000	7.100	77.40	2006
1	Radial Velocity	1	874.77400	2.210	56.95	2008
2	Radial Velocity	1	763.00000	2.600	19.84	2011
3	Radial Velocity	1	326.03000	19.400	110.62	2007
4	Radial Velocity	1	516.22000	10.500	119.47	2009
...	...	...	...	...	...	...
640	Radial Velocity	1	111.70000	2.100	14.90	2009
641	Radial Velocity	1	5.05050	1.068	44.46	2013
642	Radial Velocity	1	311.28800	1.940	17.24	1999
649	Transit	1	2.70339	1.470	178.00	2013
784	Radial Velocity	3	580.00000	0.947	135.00	2012
498 rows × 6 columns

혹은 아래처럼 출력해서 봐도 된다

planets.dropna().describe()    # 빈값을 날린 후의 대략적표

출력>
	number	orbital_period	mass	distance	year
count	498.00000	498.000000	498.000000	498.000000	498.000000
mean	1.73494	835.778671	2.509320	52.068213	2007.377510
std	1.17572	1469.128259	3.636274	46.596041	4.167284
min	1.00000	1.328300	0.003600	1.350000	1989.000000
25%	1.00000	38.272250	0.212500	24.497500	2005.000000
50%	1.00000	357.000000	1.245000	39.940000	2009.000000
75%	2.00000	999.600000	2.867500	59.332500	2011.000000
max	6.00000	17337.500000	25.000000	354.000000	2014.000000

group by 란?

-안에 있는 데이터들을 그룹지어서 확인하는 것

-언피벗된 데이터(기준이 자기 마음대로)를 의미있는 데이터로 만들어준다.

-groupby를 할 때 우리는 by(그룹을 나누는 기준열), data (그룹화해서 살펴볼 데이터), 집계함수(그룹화된 데이터를 하나의 값으로 리턴할 함수) 세가지를 지정해야한다.


Credit Amount	Type of apartment
0	1049	1
1	2799	1
2	841	1
3	2122	1
4	2171	2

△예시 데이터 프레임

 

1. Type of apartment를 groupby로 묶은 후 평균 통계를 냈을 때

german_grouped = german['Credit Amount'].groupby(german['Type of apartment'])  
german_grouped.mean()

출력>
Type of apartment
1    3122.553073
2    3067.257703
3    4881.205607
Name: Credit Amount, dtype: float64

2. 그룹 안의 그룹

german = german_sample[['Credit Amount', 'Type of apartment','Purpose']]
german_group2 = german['Credit Amount'].groupby(
                                      [german['Purpose'],                        
                                      german['Type of apartment']]
)
german_group2.mean()

출력>
Purpose  Type of apartment
0        1                    2597.225000
         2                    2811.024242
         3                    5138.689655
1        1                    5037.086957
         2                    4915.222222
         3                    6609.923077
2        1                    2727.354167
         2                    3107.450820
         3                    4100.181818
3        1                    2199.763158
         2                    2540.533040
         3                    2417.333333
4        1                    1255.500000
         2                    1546.500000
5        1                    1522.000000
         2                    2866.000000
         3                    2750.666667
6        1                    3156.444444
         2                    2492.423077
         3                    4387.266667
8        1                     902.000000
         2                    1243.875000
9        1                    5614.125000
         2                    3800.592105
         3                    4931.800000
10       2                    8576.111111
         3                    7109.000000
Name: Credit Amount, dtype: float64

이제 purpose가 가장 상위그룹되고 그 안에 아파트타입이 또 한번 그룹이 되었다.

 

3. for문에서의 그룹바이 - 가장 상위그룹이 겹치는 부분도 다 작성해줌

<예시용 표>
german = german_sample[['Type of apartment',
                       'Sex & Marital Status',
                       'Credit Amount']]

german.head() # 잘 가져와졌는지 확인


Type of apartment	Sex & Marital Status	Credit Amount
0	1	2	1049
1	1	3	2799
2	1	2	841
3	1	3	2122
4	2	3	2171

△예시용 표

<for 써서 그룹바이>
for type, g in german.groupby('Type of apartment'):
  print(g.head(n=3))
  print('--------------------------------------------------------------')

출력>
   Type of apartment  Sex & Marital Status  Credit Amount
0                  1                     2           1049
1                  1                     3           2799
2                  1                     2            841
--------------------------------------------------------------
   Type of apartment  Sex & Marital Status  Credit Amount
4                  2                     3           2171
6                  2                     3           3398
7                  2                     3           1361
--------------------------------------------------------------
    Type of apartment  Sex & Marital Status  Credit Amount
29                  3                     3           4796
44                  3                     3           1239
69                  3                     3           2032
--------------------------------------------------------------

1. 파일이 없어도 웹상의 csv파일을 불러올 수 있다 pd.read_csv('주소')

german_sample = pd.read_csv('http://freakonometrics.free.fr/german_credit.csv') # 부르기 쉽게 변수로 지정

 

2. 기초분석 (기술 통계량)

count NA를 제외한 개수
min, max 최소 / 최대값
sum
comprod 누적합
mean 평균
median 중앙값
quantile 분위수
var 표본분산
std 표본 정규분산
describe 요약 통계량

 


활용

 

german_sample = pd.read_csv('http://freakonometrics.free.fr/german_credit.csv')

△예시 소스

 

1. 불러온 데이터의 column값만 보기 : list(데이터구조)

list(german_sample.columns.values)

2. 특정 column값만 보기 : 데이터구조[['특정항목']]

german = german_sample[['Creditability', 'Duration of Credit (month)','Purpose','Credit Amount']]

3. 최소값/최대값/평균값 보기 : 데이터구조.min() / 데이터구조.max()

german.min()   
german.max()    
german.mean()

4. 전체 데이터를 맛보기식으로 보여주기 ()를 붙이면 함수가 돼서 다른 분산된 데이터를 보여주니 여기선 ()를 쓰지않는다.

데이터구조.describe

german.describe

 

5. 앞에 5개 데이터만 샘플로 보여주기

데이터구조.head()

german.head()

 

'python > [modules] Pandas' 카테고리의 다른 글

10. 데이터 정제 예시  (0) 2023.04.26
9. pandas의 핵심기능 'Group by'  (0) 2023.04.26
7. 데이터의 정렬방법  (0) 2023.04.26
6. 데이터의 기본연산  (0) 2023.04.26
5. DataFrame을 다뤄보자  (0) 2023.04.26

데이터 정렬?

데이터로 들어온 값을 어떤 기준에 위해 차순으로 정렬시키는 것

아래 두가지 방법이 있다.

 

1. <데이터구조>.sort_values()            

 데이터 크기가 작은 것 부터 정렬시킨다, (ascending=False) 옵션을 덧붙이면 높은 것부터 해준다.

 

2. <데이터구조>.sort_index(ascending=False or True)

True일 때 데이터 크기가 작은 것 부터 정렬시킨다, False일 때는 높은 것부터 해준다.


 

<예시1. <데이터구조>.sort_values() >

fruit = Series([2500,3800,1200,6000], 
               index=['apple','banana','peer','cherry'])
fruit

출력>
apple     2500
banana    3800
peer      1200
cherry    6000
dtype: int64

△예시용 시리즈

fruit.sort_values() 

출력>
peer      1200
apple     2500
banana    3800
cherry    6000
dtype: int64

높은 순/ 낮은 순 정리도 가능하다

fruit.sort_values(ascending=True) # 내림차순 정리
fruit.sort_values(ascending=False) # 높은값부터 정리

 

 

 

 

<예시2. <데이터구조>.sort_index(ascending=False or True)>

fruitData = {'fruitName':['apple','banana','cherry','peer'],
 'fruitPrice':[2500,3800,6000,1200],
 'num':[10,5,3,8]
 }

fruitName = fruitData['fruitName']

fruitFrame = DataFrame(fruitData, index = fruitName, columns = ['num','fruitPrice'])
fruitFrame

출력>

num	fruitPrice
apple	10	2500
banana	5	3800
cherry	3	6000
peer	8	1200

△예시용 데이터 프레임

fruitFrame.sort_index(ascending=False)

출력>
	num	fruitPrice
peer	8	1200
cherry	3	6000
banana	5	3800
apple	10	2500

 


 

 

+ 두가지 조건도 정렬 가능하다(대신 첫번째 조건이 먼저 성립되고 그 안에서 두번째 조건 발동)

fruitFrame.sort_values(by = ['fruitPrice','num'], ascending=[True, False]) 

출력>
	num	fruitPrice
peer	8	1200
apple	10	2500
banana	5	3800
cherry	3	6000

항목이 완벽히 일치하지 않는 두 시리즈의 연산은 일치하는 부분만 잘되고 일치하지 않는 부분은 NaN으로 표시된다.


시리즈의 경우

<예시>
fruit1 = Series([5,9,10,3],index = ['apple','banana','cherry','peer'])
fruit2 = Series([3,2,9,5,10], 
                index = ['apple','orange','banana','cherry','mango']) 

fruit1 + fruit2   

출력>
apple      8.0
banana    18.0
cherry    15.0
mango      NaN
orange     NaN
peer       NaN
dtype: float64

 

데이터 프레임의 경우

fruitData1 = {'Ohio':[4,8,3,5],'Texas':[0,1,2,3]}
fruitData2 = {'Ohio':[3,0,2,1,7],'Colorado':[5,4,3,6,0]}

fruitFrame1 = DataFrame(fruitData1, columns=['Ohio','Texas'],
                        index = ['apple','banana','cherry','peer']) 
fruitFrame2 = DataFrame(fruitData2, columns=['Ohio','Colorado'],
                        index = ['apple','orange','banana','cherry','mango'])

fruitFrame1 + fruitFrame2  

출력>
	Colorado	Ohio	Texas
apple	NaN	7.0	NaN
banana	NaN	10.0	NaN
cherry	NaN	4.0	NaN
mango	NaN	NaN	NaN
orange	NaN	NaN	NaN
peer	NaN	NaN	NaN

Pandas DataFrame으로 아래 세가지 일을 진행해보자

 

- 값 뽑아내기

-새로운 항목 추가

-항목 삭제하기

 


1. 필요한 값만 뽑아내기 

 

(1) column 방식 : 데이터프레임['행이름']

fruitFrame['fruitName']

출력>
0     apple
1    banana
2    cherry
3      peer
Name: fruitName, dtype: object

(1) 속성 방식 : 데이터프레임.속성이름

fruitFrame.fruitName

출력>
0     apple
1    banana
2    cherry
3      peer
Name: fruitName, dtype: object

 


2. 새로운 항목 추가

데이터프레임['새로운 항목이름'] = 값

 

fruitFrame['Year'] = 2023     # 존재하지 않는 columns생성
fruitFrame

출력:
	fruitPrice	num	fruitName	Year
0	2500	10	apple	2023
1	3800	5	banana	2023
2	6000	3	cherry	2023
3	1200	8	peer	2023

+ 새로 만든 항목 자리에 값이 없으면 NaN값이 들어감

variable = Series([4,2,1], index=[0,2,3])  
fruitFrame['stock'] = variable
fruitFrame

출력>

fruitPrice	num	fruitName	Year	stock
0	2500	10	apple	2023	4.0
1	3800	5	banana	2023	NaN
2	6000	3	cherry	2023	2.0
3	1200	8	peer	2023	1.

3. 항목 삭제

(1) 항목 자체 삭제

데이터구조명.drop('떨굴 데이터')

<예시용 데이터구조, 시리즈>

fruit = Series([2500,3800,1200,6000],
               index=['apple','banana','peer','cherry'])
new_fruit = fruit.drop('banana')        # 여러 항목을 숨기고 싶다면 더 써도 좋다 (예시) new_fruit = fruit.drop(['banana','apple'])  
new_fruit                              

출력>
apple     2500
peer      1200
cherry    6000
dtype: int64

이때 알아야 할 점은 banana가 원본 데이터구조에는 살아있다는 것이다.

new_fruit에서만 바나나를 삭제한 데이터를 리턴해준거지, 아예 원본에서 삭제한게 아니다

(2) 값만 삭제하기

데이터구조['삭제할 데이터'] = 0

fruit['banana'] = 0
fruit

출력>
apple     2500
banana       0
peer      1200
cherry    6000
dtype: int64

0으로 초기화 시켜준 것이다

 

(3) column 삭제하는 방법 : 데이터구조.drop('항목', axis = 0/1)

fruitPrice	num
apple	2500	10
banana	3800	5
cherry	6000	3
peer	1200	8

<△예시용 데이터프레임>

fruitFrame.drop('num', axis = 1)   

출력>

fruitPrice
apple	2500
banana	3800
cherry	6000
peer	1200

(4) DataFrame 슬라이싱

fruitFrame['banana':'cherry']  # 숫자와 달리 문자는 슬라이싱할때 문자:문자2 에서 문자2까지 포함해줌

출력>
fruitPrice	num
banana	3800	5
cherry	6000	3

'python > [modules] Pandas' 카테고리의 다른 글

7. 데이터의 정렬방법  (0) 2023.04.26
6. 데이터의 기본연산  (0) 2023.04.26
4. DataFrame 객체를 만들기  (0) 2023.04.26
3. Series 객체 다루기  (0) 2023.04.26
2. pandas를 임포트 하고 Series를 만들어보자  (0) 2023.04.26

+ Recent posts