0. Pandas 란?
파이썬 라이브러리
- 구조화된 데이터를 효과적으로 처리하고 저장
- Array 계산에 특화된 Numpy 기반으로 설계
- Numpy 의 array 가 보강된 형태, Data 와 Index 를 가지고 있음(인덱스 -데이터) 형태
1. Series 데이터
- 값을 ndarray 형태로 가지고 있음 -> 배열!!
- dtype 인자로 데이터 타입을 지정할 수 있음
- 인덱스를 지정할 수 있고 인덱스로 접근 가능
- Dictonary 활용하여 Series 생성 가능
import pandas as pd # import 해주기
int -> float
data = pd.Series([1,2,3,4], dtype = "float")
print(Data.dtype)
2. 데이터 프레임
여러개의 Series 가 모여서 행과 열을 이룬 데이터
- Dictionary -> {} 중괄호 사용
- Series -> [] 대괄호로 만들수 있음
- DataFrame-> 인덱스, 시리즈 데이터로 구성
데이터 프레임 속성 확인하는 방법
country.shape
country.size
country.ndim
country.values
데이터 프레임 index, column에 이름 지정
country.index.name = "Country"
country.columns.name = "Info"
데이터 프레임 저장 및 불러오기 기능
country.to_csv("./count.csv")
(comma separated value )
3. 데이터 선택 및 변경
.loc : 명시적인 인덱스를 참조하는 인덱싱/슬라이싱
country.loc['china'] # 인덱스가 china인 것을 구하라!
country.loc['japan':'korea', : :'population' ] # 슬라이싱
.iloc : 암묵적인 정수 인덱싱/ 슬라이싱
country.iloc[0]
country.iloc[1:3, :2]. # 슬라이싱
데이터 프레임과 시리즈의 차이!!
country['gdp'] -> 인덱스와 컬럼만 보여줌
country[['gdp']] -> 인덱스와 컬럼, 컬럼명칭까지 프레임 형태로 보여줌!! 대괄호 두개 사용할것
4. 조건 활용
Masking 연산이나 Query 함수 활용
country[country['population']<10000]
country.query("population > 10000")
5. 연산자 활용
gdp_per_capita = country['gdp'] / country['population']
6. 데이터 프레임에 데이터 추가/수정
리스트, 딕셔너리 활용
df = pd.DataFrame(columns = ['이름', '나이'])
df.loc[0] = ['길동','26']
df.loc[1] = {'이름': '철수', '나이':'24'} # 중괄호 사용하여 Dictionary
7. 새로운 컬럼 추가
NaN 컬럼 추가
df['전화번호'] = np.nan (not a number) # 새로운 컬럼 추가 후 초기화
df.loc[0,'전화번호 '] = '0101010101010' # 명시적 인덱스 활용하여 데이터 수정
8. 컬럼 삭제
df.drop('전화번호', axis = 1, inplace = True)
axis 1 -> 열방향/ 0 -> 행방향
inplace -> 원본 변경 할껀지
<실습1>
import numpy as np
import pandas as pd
# 예시) 시리즈 데이터를 만드는 방법.
series = pd.Series([1,2,3,4], index = ['a', 'b', 'c', 'd'], name="Title")
print(series, "\n")
# 국가별 인구 수 시리즈 데이터를 딕셔너리를 사용하여 만들어보세요.
dict = {
'korea' : 5180,
'japan' : 12718,
'china' : 141500,
'usa' : 32676}
country = pd.Series(dict)
print(country,"\n")
<실습2>
import numpy as np
import pandas as pd
# 두 개의 시리즈 데이터가 있습니다.
print("Population series data:")
population_dict = {
'korea': 5180,
'japan': 12718,
'china': 141500,
'usa': 32676
}
population = pd.Series(population_dict)
print(population, "\n")
print("GDP series data:")
gdp_dict = {
'korea': 169320000,
'japan': 516700000,
'china': 1409250000,
'usa': 2041280000,
}
gdp = pd.Series(gdp_dict)
print(gdp, "\n")
# 이곳에서 2개의 시리즈 값이 들어간 데이터프레임을 생성합니다.
print("Country DataFrame")
country = pd.DataFrame({'population':population,'gdp':gdp})
#Series를 합치는 방법
print(country)
<실습3>
import numpy as np
import pandas as pd
print("Masking & query")
df = pd.DataFrame(np.random.rand(5, 2), columns=["A", "B"])
print(df, "\n")
# 데이터 프레임에서 A컬럼값이 0.5보다 작고 B컬럼 값이 0.3보다 큰값들을 구해봅시다.
# 마스킹 연산을 활용하여 출력해보세요!
#country[country['population']<10000]
print(df[(df['A']<0.5) & (df['B']>0.3)])
# query 함수를 활용하여 출력해보세요!
#country.query("population > 10000")
print(df.query("A<0.5 and B>0.3"))
<실습4> 새로운 컬럼 추가
import numpy as np
import pandas as pd
# GDP와 인구수 시리즈 값이 들어간 데이터프레임을 생성합니다.
population = pd.Series({'korea': 5180,'japan': 12718,'china': 141500,'usa': 32676})
gdp = pd.Series({'korea': 169320000,'japan': 516700000,'china': 1409250000,'usa': 2041280000})
print("Country DataFrame")
country = pd.DataFrame({"population" : population,"gdp" : gdp})
print(country)
# 데이터프레임에 gdp per capita 칼럼을 추가하고 출력합니다.
gdp_per_capita = country['gdp']/country['population']
country['gdp per capita'] = gdp_per_capita
print(country)
'Data Analysis' 카테고리의 다른 글
[데이터분석] Matplotlib 데이터 시각화 1 (0) | 2021.09.26 |
---|---|
[데이터분석] Pandas 심화! 데이터 조작과 분석 (0) | 2021.09.25 |
[데이터분석] 데이터핸들링을 위한 라이브러리 NumPy (0) | 2021.09.22 |
[데이터분석] 파이썬 모듈과 라이브러리란? (1) | 2021.09.22 |
[데이터분석](Project1)코로나 확진자 데이터 분석하기 2 (0) | 2021.09.22 |