[AI][Data Analysis and Machine Learning]Pandas-DataFrame_1

·2025년 2월 21일
post-thumbnail
  • Series 가 1차원이라면 DataFrame은 2차원으로 확대된 버전
  • Excel spreadsheet 라고 생각하면 쉬움
  • 2차언이기 때문에 인덱스가 row,column로 구성됨
    • row는 각 개별 데이터를 column은 개별 속성을 의미
  • Data Analysis, Machine Learning 에서 data 변형을 위해 많이 사용
import numpy as np
import pandas as pd
import os
base_path=r'드라이브경로'
filepath = os.path.join(base_path,'titanic.csv')
pd.read_csv(filepath)
df=None
def load_titanic():
	return pd.read_csv(filepath)

DataFrame 데이터 파악

  • shape 속성( row, column)
  • describe 함수- 숫자형 데이터의 통계치 계산
  • info 함수- 데이터 타입, 각 아이템의 개수 등 출력

인덱스(index)

  • index 속성
  • 각 아이템을 특정할 수 있는 고유의 값 저장
  • 복잡한 데이터의 경우, 멀티 인덱스로 표현 가능
df.index

>RangeIndex(start=0, stop=891, step=1)

df.index.values
>array([  0,   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,  32,  33,  34,  35,  36,  37,  38,
        39,  40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51,
        52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,  64,
        65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,
        78,  79,  80,  81,  82....

컬럼(column)

  • columns 속성
  • 각각의 특성을 나타냄
  • 복잡한 데이터의 경우, 멀티 컬럼으로 표현 가능
df.columns
>Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
      
df.columns.values
>array(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'], dtype=object)

DataFrame 생성

df = pd.DataFrame([1,2,3])
df
0
01
12
23
df = pd.DataFrame([
        [1,2,3],  #첫번째 행
        [4,5,6],  #두번째 행
        ])
df
012
0123
1456

shape,ndim,size,len()

len(df)
>2

df.shape
>(2,3)

df.size
>6

df.ndim
>2

df.dtypes
0
0int64
1int64
2int64

column,index 변경

df2 = pd.DataFrame([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
],columns=['a','b','c','d'])

df2
abcd
01234
15678
29101112
#컬럼 변경
df2.columns=['국어','영어','수학','과학'
df2
국어영어수학과학
0123
1567
291011
df2.index
>RangeIndex(start=0, stop=3, step=1)

df2.index=['홍길동','둘리','마이클']
df2
국어영어수학과학
고길동1234
둘리5678
마이클9101112

dict 로 DataFrame 만들기

data={'a':100,'b':200,'c':300}
pd.DataFrame(data,index=['x'])
abc
x100200300
pd.DataFrame(data,index=['x','y','z'])
abc
x100200300
y100200300
z100200300
data={'a':[100],'b':[200],'c':[300]}
pd.DataFrame(data)
# value 가 1차원 data인 경우 index= 없이도 생성됨 
abc
0100200300

Series로 부터 DataFrame 생성

  • 각 Series 의 인덱스 →column
  • 결국 DataFrame=SeriesXSeriesX .. (Series 가 쌓인 형태가 DataFrame)
a = pd.Series([100, 200, 300], ['a', 'b', 'c'])
b = pd.Series([101, 202, 303], ['a', 'b', 'c'])
c = pd.Series([110, 220, 330], ['a', 'b', 'c'])
pd.DataFrame([a,b,c])
abc
0100200300
1101202303
2110220330
d = pd.Series([400,430,430],['a','b','d'])

pd.DataFrame([a,b,c,d])
abcd
0100.0200.0300.0NaN
1101.0202.0303.0NaN
2110.0220.0330.0NaN
3400.0430.0NaN430.0

‘특정 컬럼’의 이름 변경 rename()

df2
국어영어수학과학
고길동1234
둘리5678
마이클9101112
df2.rename(columns={'국어':'kor','과학':'Sci'})
kor영어수학Sci
고길동1234
둘리5678
마이클9101112

set_index(), reset_index()

df2.reset_index()
#기존의 index가 column 레벨로 올라오고 새로운 index 가 붙는다
index국어영어수학과학
0고길동1234
1둘리5678
2마이클9101112
df2.reset_index(drop=True)
#-> 기존의 index는 제거됨
국어영어수학과학
01234
15678
29101112
df2.set_index('국어')
#국어 컬럼이 index로 내려가고 기존의 인덱스를 대테한다.
영어수학과학
국어
1234
5678
9101112

(마찬가지로 inplace=True 하면 원본이 변경된다)

Multi-level index, Multi-level column

pd.DataFrame({'k':[10]})
k
010
pd.DataFrame({'k','k1'):[10]})
k
k1
010
pd.DataFrame({('k0','k1'):{'a':10,'b':40}})
k0
k1
a10
b40

pd.DataFrame({
    ('k', 'k1') : [10, 20, 30, 31],
    ('k', 'k2') : [40, 50, 60, 61],
    ('j', 'j1') : [70, 80, 90, 91],
    ('j', 'j2') : [100, 110, 120, 121],
}, index=[['서울', '서울', '경기', '경기'], ['평일', '휴일', '평일', '휴일']])
kj
k1k2j1j2
서울평일104070100
휴일205080110
경기평일306090120
휴일316191121

column 선택하기

  • 기본적으로 [] 는 column 추출
  • 컬럼 인덱스인 경우 인덱스의 리스트 사용 가능
    • 리스트를 전달할 경우 결과는 DataFrame
    • 하나의 컬럼명을 전달할 경우 결과는 Series
df = load_titanic()

단일 컬럼 선택

df['Survived']
Survived
00
11
21
31
40
......
8860
8871
8880
8891
8900

891 rows × 1 columns

dtype: int64

복수의 컬럼 선택하기

df['Survived'] -> 결과는 Series

df[['Survived']] -> 결과는 DataFrame 
df[['Survived','Age','Name']]
SurvivedAgeName
0022.0Braund, Mr. Owen Harris
1138.0Cumings, Mrs. John Bradley (Florence Briggs Th...
2126.0Heikkinen, Miss. Laina
3135.0Futrelle, Mrs. Jacques Heath (Lily May Peel)
4035.0Allen, Mr. William Henry
............
886027.0Montvila, Rev. Juozas
887119.0Graham, Miss. Margaret Edith
8880NaNJohnston, Miss. Catherine Helen "Carrie"
889126.0Behr, Mr. Karl Howell
890032.0Dooley, Mr. Patrick

891 rows × 3 columns

row 선택하기

DataFrame slicing

  • dataframe 의 경우 기본적으로 [] 연산은 column 선택에 사용
  • 하지만 slicing 은 row레벨로 지원한다
#10개의 row 선택 
df[:10]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaN
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaN
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123
4503Allen, Mr. William Henrymale35.0003734508.0500NaN
5603Moran, Mr. JamesmaleNaN003308778.4583NaN
6701McCarthy, Mr. Timothy Jmale54.0001746351.8625E46
7803Palsson, Master. Gosta Leonardmale2.03134990921.0750NaN
8913Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)female27.00234774211.1333NaN
9101
df[7:10]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
7803Palsson, Master. Gosta Leonardmale2.03134990921.0750NaN
8913Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)female27.00234774211.1333NaN
91012Nasser, Mrs. Nicholas (Adele Achem)female14.01023773630.0708NaN

loc,iloc 선택하기

  • Series 의 경우 [] 로 row 선택이 가능하나 DataFrame 의 경우는 기본적으로 column을 선택하도록 설계되어있다.
  • .loc[], .iloc[] 로 row 선택 가능
    • loc - 인덱스 자체를 사용
    • iloc - 0based index 로 사용
    • 위 두가지는 , 를 사용하여 column 선택도 가능하다
#index 변경
df.index += 100

df
100103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
101211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
1023

df.loc[986] #결과 Series임 
986
PassengerId887
Survived0
Pclass2
NameMontvila,Rev.Juozas
Sex
Age
SibSp
Parch
Ticket
Fare
Cabin
Embarked

dtype: object

df.loc[[986]]
# 결과 DataFrame
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
98688702Montvila, Rev. Juozasmale27.00021153613.0NaN
df.loc[[986,100,110,990]]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
98688702Montvila, Rev. Juozasmale27.00021153613.00NaN
100103Braund, Mr. Owen Harrismale22.010A/5 211717.25NaN
1101113Sandstrom, Miss. Marguerite Rutfemale4.011PP 954916.70G6
99089103Dooley, Mr. Patrickmale32.0003703767.75NaN
df.loc[np.arange(100,104)]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
100103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaN
101211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85
102313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaN
103411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.0101138
# slicing 과 loc[] 차이-loc는 인덱스였는데 얘는 백번째 행이라는 뜻
df[100:105]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
20010103Petranec, Miss. Matildafemale28.0003492457.8958NaN
20110203Petroff, Mr. Pastcho ("Pentcho")maleNaN003492157.8958NaN
20210301White, Mr. Richard Frasarmale21.0013528177.2875D26
20310403Johansson, Mr. Gustaf Joelmale33.00075408.6542NaN
20410503Gustafsson, Mr. Anders Vilhelmmale37.02031012767.9250NaN
  • iloc
#0번 인덱스가 아니라 0번째 row임 
df.iloc[0]
#결과는 Series
100
PassengerId1
Survived0
Pclass3
NameBraund, Mr. Owen Harris
Sexmale
Age22.0
SibSp1
Parch0
TicketA/5 21171
Fare7.25
CabinNaN
EmbarkedS

dtype: object

df.iloc[[0]]
#결과 DataFrame
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
100103Braund, Mr. Owen Harrismale22.010A/5 211717.25NaN
df.iloc[[0,100,200,2]]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
100103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaN
20010103Petranec, Miss. Matildafemale28.0003492457.8958NaN
30020103Vande Walle, Mr. Nestor Cyrielmale28.0003457709.5000NaN
102313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaN
df.head(3)
df[:3]
df.iloc[:3]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
100103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaN
101211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85
102313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaN

row, column 동시에 선택하기

  • loc[], iloc[] 속성을 이용 시 , 콤마를 사용하여 row column 둘 다 명시 가능

#loc[row,column] <- loc[axis0,axis1]

df.loc[986,'Survived']
>0

df.iloc[-5,-3]
>13.0

df.loc[102,'Name']
>'Heikkinen,Miss.Laina'

df.iloc[2,3]
>'Heikkinen,Miss.Laina'

df.loc['Name',102]
>'Heikkinen,Miss.Laina'

df.loc[[986,100,110,990],['Pclass','Name','Sex','Age']]
df.loc[[986,100,110,990]][['Pclass','Name','Sex','Age']]
df[['Pclass','Name','Sex','Age']].loc[[986,100,110,990]]
PclassNameSexAge
9862Montvila, Rev. Juozasmale27.0
1003Braund, Mr. Owen Harrismale22.0
1103Sandstrom, Miss. Marguerite Rutfemale4.0
9903Dooley, Mr. Patrickmale32.0

boolean selection으로 row 선택

  • numpy에서와 동일한 방식으로 해당 조건에 맞는 row만 선택
df.Pclass.unique()
>array([3,1,2])
df.Pclass.value_counts()
count
Pclass
3491
1216
2184

dtype: int64

pclass_mask = df['Pclass'] ==1
pclass_mask
Pclass
100False
101True
102False
103True
104False
......
986False
987True
988False
989True
990False

891 rows × 1 columns

dtype: bool

#boolean selection
df[pclass_mask]
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
101211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85
103411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123
106711McCarthy, Mr. Timothy Jmale54.0001746351.8625E46
1111211Bonnell, Miss. Eliza
#30대 승객에 대한 boolean mask
age_mask = (df.Age >= 30) & (df.Age<40)
# 1class 이면서 30대인 승객들 
df[age_mask & pclass_mask]

row, column 추가, 삭제

column 추가

  • [] 사용하여 추가
  • insert() 사용하여 원하는 위치에 추가
#Age*2 한 결과를 df 의 새로운 칼럼으로 추가
df['Age_Double']=df['Age']*2

df[['Age','Age_Double']].head()
AgeAge_Double
10022.044.0
10138.076.0
10226.052.0
10335.070.0
10435.070.0

파생변수

  • 기존에 존재하는 속성(변수,컬럼)으로부터 새로운 속성(컬럼)을 만들어 낸 것.
df['Age_triple']=df['Age_Double']+df['Age']
df[['Age','Age_Double','Age_triple']].head()
AgeAge_DoubleAge_triple
10022.044.066.0
10138.076.0114.0
10226.052.078.0
10335.070.0105.0
10435.070.0105.0

insert()

  • 원하는 위치에 컬럼 추가
df['Fare']/10

# 컬럼 인덱스 3 위치에 'Fare10'이라는 새로운 컬럼 삽입
df.insert(3,'Fare10',df['Fare']/10)
profile
어리둥절 빙글빙글 돌아가는 코딩세상~

0개의 댓글