import pandas as pd
data = {
'이름' : ['홍길동', '김철수', '이영희', '박민수'],
'점수' : [90, 70, 85, 95],
'반' : [2, 1, 1, 2]
}
df = pd.DataFrame(data)
print(df)
이름 점수 반
0 홍길동 90 2
1 김철수 70 1
2 이영희 85 1
3 박민수 95 2
mask = df["점수"] >= 80
filtered = df[mask]
print(filtered)
이름 점수 반
0 홍길동 90 2
2 이영희 85 1
3 박민수 95 2
# and: &
# or: |
# not: ~
# & 예시
df[(df["반"] == 1) & (df["점수"] >= 80)]
# | 예시
df[(df["반"] == 2) | (df["점수"] >= 90)]
# ~ 예시
df[~(df["점수"] >= 80)]
# isin()
# 여러 값 중에 하나에 해당하는지 여부를 판단할 때 사용
# ex. 이름이 홍길동이나 박민수일 경우
# mask = (df["이름"] == "홍길동") | (df["이름"] == "박민수")
# df[mask]
mask = df["이름"].isin(["홍길동", "박민수"])
df[mask]
mask2 = ~df["이름"].isin(["홍길동", "박민수"])
df[mask2]
# reset_index
# 조건 필터링, 행 삭제 등을 통해 인덱스가 변경됐을 시에 사용
# reset_index를 사용 -> 인덱스가 초기화
mask =(df["반"] == 2) | (df["점수"] >= 90)
df2 = df[mask]
print(df2)
# 인덱스 리셋
# df2 = df2.reset_index()
# print(df2)
# 기존 인덱스 삭제
df2 = df2.reset_index(drop = True)
print(df2)
df = pd.DataFrame({
'이름': ['민준', '서연', '지후', '서준', '지민'],
'점수': [78, 92, 85, 60, 88],
'반': [1, 2, 1, 2, 1]
})
df[df["점수"] >= 80]
# 실습 1-2. 1반 학생들 중, 점수가 85점 이상이 학생
df[(df["반"] == 1) & (df["점수"] >= 85)]
이름 점수 반
1 서연 92 2
2 지후 85 1
4 지민 88 1
df[(df["반"] == 1) & (df["점수"] >= 85)]
이름 점수 반
2 지후 85 1
4 지민 88 1
mask = df["이름"].isin(["서연", "지민"])
dff = df[mask]
print(dff)
이름 점수 반
1 서연 92 2
4 지민 88 1
df2 = dff.reset_index(drop = True)
print(df2)
이름 점수 반
0 서연 92 2
1 지민 88 1
df3 = df[(df["반"] == 2) | (df["점수"] < 80)]
print(df3)
이름 점수 반
0 민준 78 1
1 서연 92 2
3 서준 60 2
df4 = df3[df3["점수"] >= 70]
dfff = df4.reset_index(drop = True)
print(dfff)
이름 점수 반
0 민준 78 1
1 서연 92 2
df = pd.DataFrame({
'이름': ['김철수', '이영희', '박민수'],
'국어': [90, 80, 70],
'영어': [85, 78, 92]
})
df
# 같은 값을 한 번에 추가
df["반"] = '1반'
df
# 조건문을 통한 추가
df["국어_합격여부"] = df["국어"] >= 80
df
# 리스트/시리즈를 통한 열 추가
df["학번"] = [101, 102, 103]
df
# 시리즈의 연산 결과로 새 열 추가
df["총점"] = df["국어"] + df["영어"]
df
# 기존 값을 한 번에 변경
df["영어"] = 100
df
# 새로운 컬럼 추가 시, 행의 개수가 맞지 않으면 에러 발생
# df["새로운 열"] = [1, 2] # eror
# 열 삭제:drop
# 단일 열 삭제
df2 = df.drop("반", axis = 1)
df2
# 여러 열 삭제
df3 = df2.drop(["총점", "국어_합격여부"], axis = 1)
df3
# 원본에서 삭제
df.drop("반", axis = 1, inplace = True)
df
# 기타 삭제 방법 (1)
del df["국어"]
df
# 기타 삭제 방법 (2)
# deleted = df.pop("영어")
# deleted
df
df = pd.DataFrame({
'이름': ["김철수", "이영희"],
'나이': [23, 25]
})
df
# 행 추가: concat()
# 새 행을 추가하기
new_row = pd.DataFrame([{'이름': '박민수', '나이': 30}])
# df = pd.concat([df, new_row])
# 인덱스 재정렬
df = pd.concat([df, new_row], ignore_index = True)
df
# 여러 행 추가하기
new_rows = pd.DataFrame([{'이름': '동윤이', '나이': 26},
{'이름': '빠니보틀', '나이': 37}])
df = pd.concat([df, new_rows], ignore_index = True)
df
# 행 수정
# loc, iloc를 활용
df.loc[1] = ["김영희", 34]
df
df.loc[0, "나이"] = 18
df
df.loc[1:2, ["이름", "나이"]] = [["X", 20], ["Y", 10]]
df
# 행 삭제: drop
# axis 기본값은 0 -> 행 삭제
df2 = df.drop(1).reset_index(drop = True)
df2
# 여러 행 삭제
df3 = df.drop([0, 2])
df3
df = pd.DataFrame({
'이름': ['김철수', '이영희', '박민수'],
'국어': [90, 80, 70]
})
df["수학"] = [95, 100, 88]
df
이름 국어 수학
0 김철수 90 95
1 이영희 80 100
2 박민수 70 88
df2 = df.drop("이름", axis = 1)
df2
국어 수학
0 90 95
1 80 100
2 70 88
df = pd.DataFrame({
'제품': ['A', 'B'],
'가격': [1000, 2000 ]
})
new_row = pd.DataFrame([{'제품': 'C', '가격': 1500}])
df = pd.concat([df, new_row], ignore_index = True)
df
제품 가격
0 A 1000
1 B 2000
2 C 1500
df2 = df.drop(0).reset_index(drop = True)
df2
제품 가격
0 B 2000
1 C 1500
df = pd.DataFrame({
'과목': ['국어', '영어', '수학'],
'점수': [85, 90, 78]
})
mask = df[df["점수"] < 80].index
df2 = df.drop(mask).reset_index(drop = True)
df2
과목 점수
0 국어 85
1 영어 90
df2["학년"] = '1'
df2
과목 점수 학년
0 국어 85 1
1 영어 90 1
import numpy as np
df = pd.DataFrame({
'이름': ['A', 'B'],
'나이': [20, 22]
})
new_row = pd.DataFrame([{'이름': 'C', '나이': 25, '키': np.nan}])
df = pd.concat([df, new_row], ignore_index = True)
df
이름 나이 키
0 A 20 NaN
1 B 22 NaN
2 C 25 NaN
df = pd.DataFrame({
'부서': ['영업', '기획', '개발', '디자인'],
'인원': [3, 2, 5, 1]
})
mask = df[df["인원"] <= 2].index
df2 = df.drop(mask).reset_index(drop = True)
df2
부서 인원
0 영업 3
1 개발 5
df2["평가"] = "미정"
df2
부서 인원 평가
0 영업 3 미정
1 개발 5 미정
data = {
'이름' : ['홍길동', '김철수', '이영희', '박민수'],
'점수' : [90, 70, 85, 95],
'반' : [2, 1, 1, 2]
}
df = pd.DataFrame(data)
# 오름차순 정렬
df2 = df.sort_values("점수").reset_index(drop = True)
df2
# 내림차순 정렬
# ascending = False
df3 = df.sort_values("점수", ascending = False).reset_index(drop = True)
df3
# 여러 기준으로 정렬
df4 = df.sort_values(["반", "점수"], ascending=[True, False]).reset_index(drop = True)
df4
# 원본 변경
df.sort_values(["반", "점수"], ascending = [True, False], inplace = True)
df2 = df.reset_index(drop = True)
df2
# 인덱스 기준 정렬: sort_index
df_shuffled = df.sample(frac =1, random_state = 42)
df_shuffled
# 행 인덱스 기준으로 정렬
df5 = df_shuffled.sort_index() # 오름차순
df5
# 열 이름 기준 정렬(알파벳 순)
df6 = df.sort_index(axis = 1)
df6
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'David'],
'score': [88, 95, 70, 100]
})
df2 = df.sort_values("score")
df2
name score
2 Charlie 70
0 Alice 88
1 Bob 95
3 David 100
df3 = df2.reset_index(drop = False)
df3
index name score
0 2 Charlie 70
1 0 Alice 88
2 1 Bob 95
3 3 David 100
df = pd.DataFrame({
'이름': ['가', '나', '다', '라', '마'],
'반': [2, 1, 1, 2, 1],
'점수': [90, 85, 80, 95, 85]
})
df.sort_values(["반", "점수"], ascending = [True, False], inplace = True)
df
이름 반 점수
1 나 1 85
4 마 1 85
2 다 1 80
3 라 2 95
0 가 2 90
df2 = df.sort_index(axis = 1).reset_index(drop = True)
df2
반 이름 점수
0 1 나 85
1 1 마 85
2 1 다 80
3 2 라 95
4 2 가 90
df = pd.DataFrame({
'value': [10, 20, 30, 40]
}, index=[3, 1, 4, 2])
df2 = df.sort_index(axis = 0)
df2
value
1 20
2 40
3 10
4 30
df3 = df.sort_index(axis = 0, ascending = False)
print(df3)
df4 = df.sort_values("value", axis = 0, ascending = True)
print(df4)
value
4 30
3 10
2 40
1 20
value
3 10
1 20
4 30
2 40
df = pd.DataFrame({
'team': ['A', 'A', 'B', 'B', 'B', 'C'],
'name': ['Kim', 'Lee', 'Park', 'Choi', 'Jung', 'Han'],
'score': [90, 85, 80, 70, 95, 88]
})
df
# 단일 컬럼 기준 그룹화
grouped = df.groupby("team")
# 집계함수 적용
result_sum = grouped["score"].sum()
print(result_sum)
# 평균
result_mean = grouped["score"].mean()
print(result_mean)
# 개수
result_count = grouped["score"].count()
print(result_count)
df2 = pd.DataFrame({
'team': ['A', 'A', 'B', 'B', 'B', 'C'],
'gender': ['M', 'F', 'F', 'M', 'M', 'F'],
'score': [90, 85, 80, 70, 95, 88],
'age' : [21, 22, 23, 25, 20, 27]
})
df
# 여러 컬럼 기준 그룹화
result = df2.groupby(["team", "gender"])["score"].mean()
print(result)
# as_index = False 옵션
# 그룹라벨이 인덱스로 설정됨
result = df2.groupby("team", as_index=False)["score"].sum()
print(result)
# 여러 집계 함수를 한 번에 적용: agg()
result = df2.groupby("team", as_index=False)["score"].agg(['sum', 'mean', 'count'])
print(result)
# 그룹별로 여러 컬럼에 다른 집계 함수 적용
result = df2.groupby("team").agg({
"score": "mean",
"age": "max"
})
print(result)
df = pd.DataFrame({
'grade': [1, 2, 1, 2, 1, 3],
'name': ['Kim', 'Lee', 'Park', 'Choi', 'Jung', 'Han'],
'kor': [85, 78, 90, 92, 80, 75]
})
avg_kor = df.groupby('grade')
print(avg_kor["kor"].mean())
grade
1 85.0
2 85.0
3 75.0
Name: kor, dtype: float64
df = pd.DataFrame({
'class': [1, 1, 1, 2, 2, 2],
'subject': ['Math', 'Math', 'Eng', 'Math', 'Eng', 'Eng'],
'score': [80, 90, 85, 70, 95, 90]
})
result = df.groupby(["class", "subject"])["score"].agg(['mean', 'count'])
print(result)
mean count
class subject
1 Eng 85.0 1
Math 85.0 2
2 Eng 92.5 2
Math 70.0 1
df = pd.DataFrame({
'region': ['Seoul', 'Seoul', 'Busan', 'Busan', 'Daegu'],
'seller': ['A', 'B', 'A', 'B', 'A'],
'sales': [100, 200 , 150, 120, 130]
})
result = df.groupby(["region", "seller"])["sales"].agg(['sum', 'max'])
print(result)
sum max
region seller
Busan A 150 150
B 120 120
Daegu A 130 130
Seoul A 100 100
B 200 200
df = pd.DataFrame({
'team': ['A', 'A', 'B', 'B', 'A', 'B'],
'position': ['FW', 'DF', 'FW', 'DF', 'DF', 'FW'],
'score': [3, 2, None,1, 4, 2]
})
df2 = df.fillna(0) # 결측치를 0으로 변환
result = df2.groupby(["team", "position"])["score"].mean()
print(result)
team position
A DF 3.0
FW 3.0
B DF 1.0
FW 1.0
Name: score, dtype: float64
df = pd.DataFrame({
'dept': ['HR', 'HR', 'IT', 'IT', 'Sales', 'Sales'],
'gender': ['M', 'F', 'F', 'M', 'F', 'F'],
'salary': [3500 , 3200 , 4000 , 4200 , 3000 , 3100]
})
result = df.groupby(["dept", "gender"])["salary"].agg(["count", "sum"])
print(result)
count sum
dept gender
HR F 1 3200
M 1 3500
IT F 1 4000
M 1 4200
Sales F 2 6100
import pandas as pd
df = pd.read_csv("./dataset/practice_book_dataset.csv")
df.head()
df.shape
df.dtypes
df.info()
df.describe()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 830 entries, 0 to 829
Data columns (total 19 columns):
Column Non-Null Count Dtype
0 title 830 non-null object
1 author 657 non-null object
2 price 722 non-null float64
3 price (including used books) 722 non-null object
4 pages 745 non-null object
5 avg_reviews 702 non-null float64
6 n_reviews 702 non-null object
7 star5 702 non-null object
8 star4 635 non-null object
9 star3 554 non-null object
10 star2 451 non-null object
11 star1 328 non-null object
12 dimensions 644 non-null object
13 weight 651 non-null object
14 language 759 non-null object
15 publisher 714 non-null object
16 ISBN_13 665 non-null object
17 link 830 non-null object
18 complete_link 830 non-null object
dtypes: float64(2), object(17)
memory usage: 123.3+ KB
price avg_reviews
count 722.000000 702.000000
mean 46.491537 4.472080
std 63.292394 0.409608
min 0.990000 1.000000
25% 23.725000 4.325000
50% 39.490000 4.500000
75% 51.990000 4.700000
max 1318.740000 5.000000
df[["title", "author"]].head(10)
title author
0 Data Analysis Using R (Low Priced Edition): A ... [ Dr Dhaval Maheta]
1 Head First Data Analysis: A learner's guide to... NaN
2 Guerrilla Data Analysis Using Microsoft Excel:... [ Oz du Soleil, and , Bill Jelen]
3 Python for Data Analysis: Data Wrangling with ... [ William McKinney]
4 Excel Data Analysis For Dummies (For Dummies (... [ Paul McFedries]
5 Everything Data Analytics: A Beginner's Guide ... NaN
6 SQL for Data Analysis: Advanced Techniques for... [ Cathy Tanimura]
7 Qualitative Data Analysis: A Methods Sourcebook [ Matthew B. Miles, A. Michael Huberman, et al.]
8 Topological Data Analysis with Applications [ Gunnar Carlsson, and , Mikael Vejdemo-Johan...
9 R in Action, Third Edition: Data analysis and ... [ Robert I. Kabacoff]
df2 = df.copy()
df2["library"] = "seoul library"
df2.to_csv("./dataset/new_book_dataset.csv")
mask = df["price"] >= 100
df[mask]
df.loc[mask, ["title", "price", "avg_reviews"]]
title price avg_reviews
46 Exploratory Data Analysis (Classic Version) (P... 105.99 4.9
80 An Introduction to Categorical Data Analysis 121.99 4.4
101 Big Data Analytics in Earth, Atmospheric and O... 161.06 NaN
102 Pharmacokinetic and Pharmacodynamic Data Analy... 233.60 4.4
113 Econometric Analysis of Cross Section and Pane... 115.00 4.5
157 Spreadsheet Modeling and Decision Analysis: A ... 153.50 4.4
167 Astronomical Image and Data Analysis (Astronom... 158.55 NaN
169 Spatial Analysis with R 101.01 5.0
173 Adjustment Computations: Spatial Data Analysis 104.95 4.5
178 Longitudinal Data Analysis 155.57 4.9
191 Clinical Genomics, Second Edition: A Guide to ... 200.00 NaN
195 Categorical Data Analysis 113.19 4.7
204 The Statistical Sleuth: A Course in Methods of... 127.98 4.0
222 Geographic Data Science with Python (Chapman &... 170.00 NaN
242 Data Structures & Algorithm Analysis in C++ 193.32 4.2
248 Statistics, Data Analysis, and Decision Modeling 250.63 4.1
255 Design and Analysis of Experiments with R (Cha... 103.32 4.5
269 An Introduction to Statistical Methods and Dat... 154.94 4.2
280 The Analysis of Biological Data 146.12 4.3
298 Business Analytics: Data Analysis & Decision M... 125.49 4.5
302 Statistics and Data Analysis for Nursing Research 125.60 4.3
304 The Statistical Analysis of Functional MRI Dat... 100.33 5.0
310 Applied Survival Analysis: Regression Modeling... 112.03 4.3
337 Statistics and Data Analysis: From Elementary ... 146.65 4.4
396 Introduction to Synthetic Aperture Radar Using... 151.59 5.0
556 Starting Out with Python 139.99 4.6
599 Applied Time Series Analysis and Forecasting w... 147.77 NaN
616 Introduction to Radar With Python and Matlab 159.00 4.2
638 Database Technologies: Concepts, Methodologies... 743.47 NaN
658 Algorithmic Finance: A Companion To Data Science 119.21 3.5
661 Machine Learning with Quantum Computers (Quant... 101.24 4.6
677 The Basics of Data Literacy: Helping Your Stud... 287.14 4.6
686 Business Intelligence, Analytics, and Data Sci... 111.99 4.5
695 Cybersecurity Data Science: Best Practices in ... 165.80 4.0
720 Pattern Recognition and Machine Learning (Info... 105.22 4.6
734 Research Anthology on Machine Learning Techniq... 1318.74 NaN
763 The SAGE Handbook of Social Media Research Met... 139.56 NaN
769 Analytics, Data Science, & Artificial Intellig... 223.00 4.3
808 Introduction to Data Mining (2nd Edition) (Wha... 104.83 4.0
813 Data Science for Engineers 120.00 NaN
df = pd.read_excel("./dataset/practice_employee_dataset.xlsx")
df.head(5)
df2 = df.copy()
df2["Working Period"] = 3
df2.to_excel("./dataset/New_employee_dataset.xlsx")
df2.head(10)
df = pd.read_excel("./dataset/dataset2.xlsx")
df.head()
df_sheet = pd.read_excel("./dataset/dataset2.xlsx", sheet_name = "테스트")
df_sheet.head()
df = pd.read_json(r"C:\Users\bdy00\Desktop\KD_RE_5th_python\DataAnalysis\dataset\practice_json.json")
df.head()