import pandas as pd
data = pd.Series([1, 2, 3, 4])
# index data
# 0 1
# 1 2
# 2 3
# 3 4
# dtype: int64
data = pd.Series([1,2,3,4], index=['a','b','c','d'])
# index data
# a 1
# b 2
# c 3
# d 4
# dtype: int64
data['b'] # 2
dic = {'apple':1, 'bad':2, 'car':3, 'deal':4}
dic_series = pd.Series(dic)
# apple 1
# bad 2
# car 3
# deal 4
# dtype: int64
dic_series.keys
# <bound method Series.keys of
# apple 1
# bad 2
# car 3
# deal 4
# dtype: int64>
dic_series.values
# array([1, 2, 3, 4], dtype=int64)
dic_series.items
# <bound method Series.items of
# apple 1
# bad 2
# car 3
# deal 4
# dtype: int64>
kor_dict = {'a':70, 'b':90, 'c':100, 'd':65}
math_dict = {'a':20, 'b':85, 'c':95, 'd':80}
kor = pd.Series(kor_dict)
math = pd.Series(math_dict)
df = pd.DataFrame({
'kor': kor,
'math': math})
# kor math
# a 70 20
# b 90 85
# c 100 95
# d 65 80
df.index # Index(['a', 'b', 'c', 'd'], dtype='object')
df.columns # Index(['kor', 'math'], dtype='object')
df['kor']
# a 70
# b 90
# c 100
# d 65
# Name: kor, dtype: int64
country.to_csv("./country.csv") # csv로 저장
country.to_excel("./country.xlsx") # excel file로 저장
country = pd.read_csv("./country.csv") # csv file 불러오기
country = pd.read_excel("./country.xlsx") # excel file 불러오기
df = pd.DataFrame({
'kor': kor,
'math': math})
# kor math
# a 70 20
# b 90 85
# c 100 95
# d 65 80
df.loc['a'] # 명시적인 인덱싱
# kor 70
# math 20
# Name: a, dtype: int64
df.loc['a':'c', 'kor']
# a 70
# b 90
# c 100
# Name: kor, dtype: int64
df.iloc[0] # 파이썬 스타일 정수 인덱싱
# kor 70
# math 20
# Name: a, dtype: int64
df.iloc[0:3, 0]
# a 70
# b 90
# c 100
# Name: kor, dtype: int64
df = pd.DataFrame(columns=['이름', '나이', '주소'])
df.loc[0] = ['김영희', 27, '서울']
df.loc[1] = {'이름': '이철수', '나이': 27, '주소':'서울'}
# 이름 나이 주소
# 0 김영희 27 서울
# 1 이철수 27 서울
df.loc[1, '나이'] = 29
# 이름 나이 주소
# 0 김영희 27 서울
# 1 이철수 29 서울
df['전화번호'] = np.nan # 이렇게 하지 않고 바로 할당해도 들어간다. 안 들어간 값은 NaN.
df.loc[0, '전화번호'] = '01012345678'
# 이름 나이 주소 전화번호
# 0 김영희 27 서울 01012345678
# 1 이철수 29 서울 NaN
df['이름']
# 0 김영희
# 1 이철수
# Name: 이름, dtype: object
df[['이름','주소','나이']]
# 이름 주소 나이
# 0 김영희 서울 27
# 1 이철수 서울 29
A = pd.Series([2,4,6], index=[0,1,2])
B = pd.Series([1,3,5], index=[1,2,3])
A + B
# 0 NaN
# 1 5.0
# 2 9.0
# 3 NaN
# dtype: float64
A.add(B, fill_value=0)
# 0 2.0
# 1 5.0
# 2 9.0
# 3 5.0
# dtype: float64
출처: 엘리스 AI트랙 3기 11주차 수업