«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Recent Posts
Today
Total
관리 메뉴

짜리몽땅 매거진

[Python] 반복문의 데이터프레임 접근 본문

Data/Python

[Python] 반복문의 데이터프레임 접근

쿡국 2023. 9. 29. 22:45

반복문 복습과 데이터프레임 적용

 

  • 반복문 : 데이터프레임 전처리 과정에서 다양한 데이터를 빠르게 전처리하기 위해서는 반복문이 필요하다!
import pandas as pd

df = pd.read_csv('mpg.csv')

df

manufacturer	model	displ	year	cyl	trans	drv	cty	hwy	fl	category
0	audi	a4	1.8	1999	4	auto(l5)	f	18	29	p	compact
1	audi	a4	1.8	1999	4	manual(m5)	f	21	29	p	compact
2	audi	a4	2.0	2008	4	manual(m6)	f	20	31	p	compact
3	audi	a4	2.0	2008	4	auto(av)	f	21	30	p	compact
4	audi	a4	2.8	1999	6	auto(l5)	f	16	26	p	compact
...	...	...	...	...	...	...	...	...	...	...	...
229	volkswagen	passat	2.0	2008	4	auto(s6)	f	19	28	p	midsize
230	volkswagen	passat	2.0	2008	4	manual(m6)	f	21	29	p	midsize
231	volkswagen	passat	2.8	1999	6	auto(l5)	f	16	26	p	midsize
232	volkswagen	passat	2.8	1999	6	manual(m5)	f	18	26	p	midsize
233	volkswagen	passat	3.6	2008	6	auto(s6)	f	17	26	p	midsize
234 rows × 11 columns

for i in df:
    print(i)

manufacturer
model
displ
year
cyl
trans
drv
cty
hwy
fl
category

# 단순히 데이터프레임의 컬럼 값들을 출력하는 것은 의미 X
# 반복문을 응용하자

# 이 두개의 연비 평균을 내면, 차량의 평균 연비가 나온다.
for i,j in zip(df.cty, df.hwy):
    print((i+j)/2)

새로운 칼럼을 추가하고, 필터링을 걸어 원하는 값만 출력해보자

# 데이터프레임에 새로운 칼럼을 넣어보자

mc = [] # -->연비 평균 칼럼 추가하자
for i,j in zip(df.cty, df.hwy):
    mc.append((i+j)/2)
    
df['mc']=mc  #데이터프레임에 새로운 칼럼 넣는 법    

df

	manufacturer	model	displ	year	cyl	trans	drv	cty	hwy	fl	category	mc
0	audi	a4	1.8	1999	4	auto(l5)	f	18	29	p	compact	23.5
1	audi	a4	1.8	1999	4	manual(m5)	f	21	29	p	compact	25.0
2	audi	a4	2.0	2008	4	manual(m6)	f	20	31	p	compact	25.5
3	audi	a4	2.0	2008	4	auto(av)	f	21	30	p	compact	25.5
4	audi	a4	2.8	1999	6	auto(l5)	f	16	26	p	compact	21.0
...	...	...	...	...	...	...	...	...	...	...	...	...
229	volkswagen	passat	2.0	2008	4	auto(s6)	f	19	28	p	midsize	23.5
230	volkswagen	passat	2.0	2008	4	manual(m6)	f	21	29	p	midsize	25.0
231	volkswagen	passat	2.8	1999	6	auto(l5)	f	16	26	p	midsize	21.0
232	volkswagen	passat	2.8	1999	6	manual(m5)	f	18	26	p	midsize	22.0
233	volkswagen	passat	3.6	2008	6	auto(s6)	f	17	26	p	midsize	21.5
234 rows × 12 columns

df.info()
#데이터 분석시 문자열, 수치형에 대해서는 분석전에 전처리 또는 시각화하는 방법이 다르다.
#데이터 타입에 따라서 데이터를 나눠서 보는 것도 좋은 방법 중 하나다!

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 234 entries, 0 to 233
Data columns (total 12 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   manufacturer  234 non-null    object 
 1   model         234 non-null    object 
 2   displ         234 non-null    float64
 3   year          234 non-null    int64  
 4   cyl           234 non-null    int64  
 5   trans         234 non-null    object 
 6   drv           234 non-null    object 
 7   cty           234 non-null    int64  
 8   hwy           234 non-null    int64  
 9   fl            234 non-null    object 
 10  category      234 non-null    object 
 11  mc            234 non-null    float64
dtypes: float64(2), int64(4), object(6)
memory usage: 22.1+ KB

df['year'].dtype #각 칼럼별 데이터타입도 출력할 수 있다.
dtype('int64')

for i in df.columns:
    print(df[i].dtype)

object
object
float64
int64
int64
object
object
int64
int64
object
object
float64

for i in df.columns:
    df_type = df[i].dtype
    if df_type =='object':
        print(i, df_type)
        #타입에 대한 것을 변수에 넣고, 칼럼과 데이터타입 함께 출력

manufacturer object
model object
trans object
drv object
fl object
category object

데이터프레임은 자료형에 따라서도 구조를 나눌 수 있다.

자료형에 따라서 데이터를 나눠서 출력할 수 있다.

  • 수치형 데이터
  • 문자형 데이터
  • 시계열도 있고 기타 다른 데이터타입도 있지만...
df2 = pd.read_csv('spam.csv')

df2

Unnamed: 0	target	text
0	0	ham	Go until jurong point, crazy.. Available only ...
1	1	ham	Ok lar... Joking wif u oni...
2	2	spam	Free entry in 2 a wkly comp to win FA Cup fina...
3	3	ham	U dun say so early hor... U c already then say...
4	4	ham	Nah I don't think he goes to usf, he lives aro...
...	...	...	...
5569	5569	spam	This is the 2nd time we have tried 2 contact u...
5570	5570	ham	Will ü b going to esplanade fr home?
5571	5571	ham	Pity, * was in mood for that. So...any other s...
5572	5572	ham	The guy did some bitching but I acted like i'd...
5573	5573	ham	Rofl. Its true to its name
5574 rows × 3 columns

df2_1 = df2['text'][0]

df2_1
'Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...'

import string # 특수문자 제거를 위해 string 임포트

string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

for i in df2_1:
    if i not in string.punctuation:
        print(i, end='')
        
Go until jurong point crazy Available only in bugis n great world la e buffet Cine there got amore wat

for i in df2_1:
    if i in string.punctuation:
        print(i, end='')
        
,........

* 추가 과제 1

 

리스트를 내포한 실제 반복문 코드를 데이터프레임에 적용해보자

 

import pandas as pd

df = pd.read_excel('excel_exam.xlsx')

df

id	nclass	math	english	science
0	1	1	50	98	50
1	2	1	60	97	60
2	3	1	45	86	78
3	4	1	30	98	58
4	5	2	25	80	65
5	6	2	50	89	98
6	7	2	80	90	45
7	8	2	90	78	25
8	9	3	20	98	15
9	10	3	50	98	45
10	11	3	65	65	65
11	12	3	45	85	32
12	13	4	46	98	65
13	14	4	48	87	12
14	15	4	75	56	78
15	16	4	58	98	65
16	17	5	65	68	98
17	18	5	80	78	90
18	19	5	89	68	87
19	20	5	78	83	58

mean = []
for i,j,k in zip(df.math, df.english,df.science):
    mean.append((i+j+k)/3)
#1. 각 과목별 점수 평균 구하기

df['mean']=mean

df
id	nclass	math	english	science	mean
0	1	1	50	98	50	66.000000
1	2	1	60	97	60	72.333333
2	3	1	45	86	78	69.666667
3	4	1	30	98	58	62.000000
4	5	2	25	80	65	56.666667
5	6	2	50	89	98	79.000000
6	7	2	80	90	45	71.666667
7	8	2	90	78	25	64.333333
8	9	3	20	98	15	44.333333
9	10	3	50	98	45	64.333333
10	11	3	65	65	65	65.000000
11	12	3	45	85	32	54.000000
12	13	4	46	98	65	69.666667
13	14	4	48	87	12	49.000000
14	15	4	75	56	78	69.666667
15	16	4	58	98	65	73.666667
16	17	5	65	68	98	77.000000
17	18	5	80	78	90	82.666667
18	19	5	89	68	87	81.333333
19	20	5	78	83	58	73.000000

for index, row in df.iterrows():
    if row['math'] > 50:
        print(int(row['id']),',',int(row['math']))
#2. 수학점수 50점이 넘을 경우, 학생id, 수학점수 출력
2 , 60
7 , 80
8 , 90
11 , 65
15 , 75
16 , 58
17 , 65
18 , 80
19 , 89
20 , 78

import numpy as np

for i in df:
    print(i)
#3. 데이터프레임의 칼럼 출력하기

id
nclass
math
english
science
mean

* 추가 과제2

 

  • mpg 데이터의 조건문을 2개 또는 3개 이상 필터해서 값을 출력
  • e.g) 1.제조사는 아우디, 2. 연도는 2008년, 3. 평균연비는 20이상 # 3개의 조건을 한 번에 걸어서 특정 값을 출력
import pandas as pd

df = pd.read_csv('mpg.csv')

df
manufacturer	model	displ	year	cyl	trans	drv	cty	hwy	fl	category
0	audi	a4	1.8	1999	4	auto(l5)	f	18	29	p	compact
1	audi	a4	1.8	1999	4	manual(m5)	f	21	29	p	compact
2	audi	a4	2.0	2008	4	manual(m6)	f	20	31	p	compact
3	audi	a4	2.0	2008	4	auto(av)	f	21	30	p	compact
4	audi	a4	2.8	1999	6	auto(l5)	f	16	26	p	compact
...	...	...	...	...	...	...	...	...	...	...	...
229	volkswagen	passat	2.0	2008	4	auto(s6)	f	19	28	p	midsize
230	volkswagen	passat	2.0	2008	4	manual(m6)	f	21	29	p	midsize
231	volkswagen	passat	2.8	1999	6	auto(l5)	f	16	26	p	midsize
232	volkswagen	passat	2.8	1999	6	manual(m5)	f	18	26	p	midsize
233	volkswagen	passat	3.6	2008	6	auto(s6)	f	17	26	p	midsize
234 rows × 11 columns

mc = []
for i,j in zip(df.cty, df.hwy):
    mc.append((i+j)/2)
df['mc'] =mc
df

manufacturer	model	displ	year	cyl	trans	drv	cty	hwy	fl	category	mc
0	audi	a4	1.8	1999	4	auto(l5)	f	18	29	p	compact	23.5
1	audi	a4	1.8	1999	4	manual(m5)	f	21	29	p	compact	25.0
2	audi	a4	2.0	2008	4	manual(m6)	f	20	31	p	compact	25.5
3	audi	a4	2.0	2008	4	auto(av)	f	21	30	p	compact	25.5
4	audi	a4	2.8	1999	6	auto(l5)	f	16	26	p	compact	21.0
...	...	...	...	...	...	...	...	...	...	...	...	...
229	volkswagen	passat	2.0	2008	4	auto(s6)	f	19	28	p	midsize	23.5
230	volkswagen	passat	2.0	2008	4	manual(m6)	f	21	29	p	midsize	25.0
231	volkswagen	passat	2.8	1999	6	auto(l5)	f	16	26	p	midsize	21.0
232	volkswagen	passat	2.8	1999	6	manual(m5)	f	18	26	p	midsize	22.0
233	volkswagen	passat	3.6	2008	6	auto(s6)	f	17	26	p	midsize	21.5
234 rows × 12 columns

# 1 : 제조사 아우디, 연도 2000년 이전, 평균연비 23이상
for i,j,k in zip(df.manufacturer,df.year,df.mc):
    if i =='audi' and j<2000 and k>=23:
        print(i,j,k)

audi 1999 23.5
audi 1999 25.0

# 2 : 제조사 아우디, 모델은 a4
for i,j in zip(df.manufacturer,df.model):
    if i =='audi' and j=='a4':
        print(i,j)

audi a4
audi a4
audi a4
audi a4
audi a4
audi a4
audi a4

# 3 : 제조사 폭스바겐, 배기량 2.5 이상
for i,j in zip(df.manufacturer,df.displ):
    if i =='volkswagen' and j>=2.5:
        print(i,j)
        
volkswagen 2.8
volkswagen 2.5
volkswagen 2.5
volkswagen 2.8
volkswagen 2.8
volkswagen 2.5
volkswagen 2.5
volkswagen 2.8
volkswagen 2.8
volkswagen 3.6