PYTHON/강의복습

[22.10.19] 판다스 ( Seriese / 데이터프레임 / 인덱스 )

peach_h 2022. 10. 19. 12:34

판다스는 Series와 데이터프레임 구조를 가진다.

 

Series

Series를 생성하면, 인덱스가 생성되고 value값이 들어감.

import pandas as pd

#print('판다스 버젼 ' , pd.__version__) 1.5버젼

list1 = [ 31,100,73, 28, -7 ,39]
print(list1)
s1 = pd.Series(list1)
print(s1)

기존의 리스트 구조에서 인덱스가 형성되고 value가 들어간 모습

Series는 기존의 dict와 아주 유사해보인다.

 

 

 

dict의 Series화

dict를 판다스의 Series화 하기도 가능함 !

dict5 = { 'aa':'apple', 'bb':'blue', 'cc':'cherry'}
print(dict5)

s5 = pd.Series(dict5)
print(s5)

key값은 인덱스로, value는 값으로 들어감 !

 

 

 

Series Index 바꾸기

판다스 Series의 특징은 인덱스를 내맘대로 바꿀 수 있다는 점.

s7 = pd.Series( [9800, 2300, 4500 ] , index=['수박','포도','단감'])
print(s7)

print(s7.loc['수박'])
print(s7.iloc[1])

s8 = pd.Series( [9800, 2300, 4500 ] , ['제주','독도','홍도'])
print(s8)

이렇게 다양한 방식으로 index를 내맘대로 설정할 수 있다.

 

 명시적 인덱스  : 이렇게 인덱스를 따로 지정했을 때  / data.loc[인덱스] ->

 묵시적 인덱스  : 자동 생성된 01234... / data.iloc[인덱스]

 

 

묵시적(암묵적) 인덱스를 슬라이싱 했을 때는 뒤에 지정된 인덱스가 제외된다 !!

tbl = pd.DataFrame({
    'weight' : [ 80.0, 76.0, 46.7, 51.2, 78.9, 65.5] ,
    'height' : [ 170, 180, 156, 160, 190, 164],
    'gender' : ['m','m', 'f', 'f', 'm','m']
})

print(tbl)
print('데이터추출 ')
print(tbl[2:4] )

[2:4]를 지정하면 2, 3행이 나오는걸 확인함

 

 

 

조건 출력하기
# weight 70이상 출력
print(tbl[tbl['weight']>=70])
print('-' * 100)

# gender m 출력
print(tbl[tbl.gender =='m'])
print('-' * 100)
print(tbl[tbl['gender']=='m'])

tbl.gender >= 'm' 과 tbl['gender']>='m'이 동일함을 확인함

인덱스를 지정하지 않고, 조건으로도 원하는 행을 추출할 수 있다.

 

 

 

데이터 정렬하기
print(tbl.sort_values(by='weight', ascending=False, ignore_index=False))
print('-' * 100)
print(tbl.sort_values(by='weight', ascending=False,  ignore_index=True))

내림차순 정렬 : ascending = False

오름차순 정렬 : ascending = True

 

정렬 후 인덱스 유지 : ignore_index = False

정렬 후 인덱스도 재정렬 : ignore_index = True

 

 

 

다양한 데이터 프레임 만들어보기
bts = {
    'busan': {2019:3.4, 2020:7.9},
    'suwon': {2019:12.5, 2020:6.5}
}
df = pd.DataFrame(bts)
print(df)


data2 = pd.DataFrame({
    'name' : [ '제니', '길동', '둘리', '영우', '라미'] ,
    'year' : [ 2001, 1987, 2300, 2002,  2001],
    'point' : [1.2, 4.5, 8.1, 9.3, 3.6]
})
df2 = pd.DataFrame(data2 , columns=['name','year', 'point'])
print(df2)

data3 = [
     [ '미란', 2001, 1.2 ],
     [ '영희', 1987, 4.5] ,
     [ '라미', 2003, 8.1]
    ]
df3 = pd.DataFrame(data3,columns=['이름','년도', '점수'],index=['A','B','C'] )
print(df3)

 

판다스는 역시 R과 유사한 부분이 많은 것 같다.