본문 바로가기

Python/Pandas

Pandas_02

반응형
day2_pandas2
In [2]:
import numpy as np
import pandas as pd

DataFrame 생성하기

  • 데이타프레임이름 = pd.DataFrame(딕셔너리리스트)
  • 딕셔너리 리스트 : 딕셔너리 구조인데 값이 리스트인 구조
  • 데이타프레임을 딕셔너리 리스트로 만들면 키는 컬럼명으로 지정된다.
{ 키1:[리스트1], 키2:[리스트2] ... }

딕셔너리 리스트 생성하기

{   키1:[값1, 값2, 값3 ...],
    키2:[값1, 값2, 값3 ...] ... }
In [5]:
data = {   "name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
           "year":[2014, 2015, 2016, 2017, 2018],
           "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
data
Out[5]:
{'name': ['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
 'year': [2014, 2015, 2016, 2017, 2018],
 'points': [1.5, 1.7, 3.6, 2.5, 2.9]}
In [7]:
data['name']
Out[7]:
['Elise', 'Julia', 'Jhon', 'Charles', 'Charles']
In [10]:
data['points']
Out[10]:
[1.5, 1.7, 3.6, 2.5, 2.9]

딕셔너리 리스트를 데이타프레임으로 생성하기

In [12]:
# 딕셔너리 리스트의 키값이 컬럼명으로 지정된다. 
df = pd.DataFrame(data)
df
Out[12]:
name year points
0 Elise 2014 1.5
1 Julia 2015 1.7
2 Jhon 2016 3.6
3 Charles 2017 2.5
4 Charles 2018 2.9

DataFrame 생성하기 - Nested Dictionary 이용

  • Nested Dictionary란? 딕셔너리 안에 딕셔너리가 정의된 구조

    {키1: {키1-1:값1, 키1-2:값2 ... }, 키2: {키2-1:값1, 키2-2:값2 ... }}
  • 데이타프레임 생성시 메인 키는 컬럼으로 서브키는 행의 인덱스로 설정

In [13]:
pop =  {'Nevada':{2001:2.4, 2002:2.9},
        'Ohio':{2000:1.5, 2001:1.7, 2002:3.6} }
pop
Out[13]:
{'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}
In [14]:
pop['Nevada']
Out[14]:
{2001: 2.4, 2002: 2.9}
In [32]:
df = pd.DataFrame(pop)
df
Out[32]:
Nevada Ohio
2000 NaN 1.5
2001 2.4 1.7
2002 2.9 3.6

데이타프레임의 컬럼은 시리즈이다.

In [33]:
df['Nevada']
Out[33]:
2000    NaN
2001    2.4
2002    2.9
Name: Nevada, dtype: float64
In [34]:
type(df['Nevada'])
Out[34]:
pandas.core.series.Series

데이타프레임의 데이타형 확인하기

In [35]:
type(df)
Out[35]:
pandas.core.frame.DataFrame

행으로 필터링하기

데이타프레임명.iloc[인덱스번호, :]
데이타프레임명.loc[행의인덱스이름]
In [27]:
df.iloc[0,:]
Out[27]:
Nevada    NaN
Ohio      1.5
Name: 2000, dtype: float64
In [31]:
df.loc[2000]
Out[31]:
Nevada    NaN
Ohio      1.5
Name: 2000, dtype: float64

DataFrame의 속성

  • 데이타프레임의 행 요소 조회 – 데이타프레임이름.index
  • 데이타프레임의 열 요소 조회 – 데이타프레임이름.columns
  • 데이타프레임의 요소 값 조회 – 데이타프레임이름.values => 넘파이배열
  • 데이타프레임 전체갯수 – 데이타프레임이름.size => 정수
  • 데이타프레임 구조 – 데이타프레임이름.shape => 튜플구조 (행수,열수)
  • 데이타프레임 컬럼별 데이터형 – 데이타프레임이름[컬럼명].dtype
In [36]:
data = { "name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
         "year":[2014, 2015, 2016, 2017, 2018],
         "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
In [37]:
df = pd.DataFrame(data)
df
Out[37]:
name year points
0 Elise 2014 1.5
1 Julia 2015 1.7
2 Jhon 2016 3.6
3 Charles 2017 2.5
4 Charles 2018 2.9
In [38]:
df.index
Out[38]:
RangeIndex(start=0, stop=5, step=1)
In [39]:
df.columns
Out[39]:
Index(['name', 'year', 'points'], dtype='object')

데이타프레임의 실제 값은 넘파이배열 형태이다.

In [40]:
df.values
Out[40]:
array([['Elise', 2014, 1.5],
       ['Julia', 2015, 1.7],
       ['Jhon', 2016, 3.6],
       ['Charles', 2017, 2.5],
       ['Charles', 2018, 2.9]], dtype=object)
In [41]:
type(df.values)
Out[41]:
numpy.ndarray

2차원 구조

In [42]:
df.shape
Out[42]:
(5, 3)

전체 갯수

In [43]:
df.size
Out[43]:
15

컬럼별 데이타형 확인하기

In [48]:
# 문자열 형태는 dtype('O') 로 출력 
df['name'].dtype
Out[48]:
dtype('O')
In [46]:
df['year'].dtype
Out[46]:
dtype('int64')
In [47]:
df['points'].dtype
Out[47]:
dtype('float64')

DataFrame의 행, 열의 대표이름 정의하기

  • 데이타프레임의 행이름 정의 – 데이타프레임이름.index.name
  • 데이타프레임의 열이름 정의– 데이타프레임이름.columns.name
In [49]:
# 딕셔너리 리스트 정의 
data = {'Math':[100, 45, 89, 40],
       'Eng':[80, 95, 88, 77],
       'Sci':[100, 77, 89, 100]}

# 인덱스 지정 => 데이타프레임 
df = pd.DataFrame(data, index=['Jullia', 'Maria', 'Jhon', 'Tom'])
df
Out[49]:
Math Eng Sci
Jullia 100 80 100
Maria 45 95 77
Jhon 89 88 89
Tom 40 77 100
In [52]:
# 컬럼과 인덱스에 대표이름 정의
df.index.name = "[ Student ]"
df.columns.name = "[ Subject ]"
df
Out[52]:
[ Subject ] Math Eng Sci
[ Student ]
Jullia 100 80 100
Maria 45 95 77
Jhon 89 88 89
Tom 40 77 100

DataFrame 생성하기 - 인덱스명, 컬럼명 지정

데이타프레임이름 = pd.DataFrame(딕셔너리, columns=[컬럼리스트],
                                    index=[인덱스리스트])
In [59]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
data
Out[59]:
{'name': ['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
 'year': [2014, 2015, 2016, 2017, 2018],
 'points': [1.5, 1.7, 3.6, 2.5, 2.9]}

컬럼명 순서가 위에 data의 key의 순서와 같다

In [60]:
df = pd.DataFrame(data)
df
Out[60]:
name year points
0 Elise 2014 1.5
1 Julia 2015 1.7
2 Jhon 2016 3.6
3 Charles 2017 2.5
4 Charles 2018 2.9

인덱스,컬럼명과 함께 데이타프레임 정의하기

컬럼명 순서가 아래의 columns의 순서와 같다

In [61]:
df = pd.DataFrame(data, columns=["year", "name", "points"], 
                    index=["one", "two", "three", "four", "five"])
df
Out[61]:
year name points
one 2014 Elise 1.5
two 2015 Julia 1.7
three 2016 Jhon 3.6
four 2017 Charles 2.5
five 2018 Charles 2.9

Dataframe 의 재정의 – 새로운 컬럼 추가

  • 데이타 프레임 생성시 열값이 없는 경우에는 NaN으로 지정
  • NaN(Not a Number)

데이타프레임 생성시 columns 이용

In [75]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9]}

# "penalty" 새로운 컬럼 추가 
df = pd.DataFrame(data, columns=["year", "name", "points","penalty"], 
                    index=["one", "two", "three", "four", "five"])
df
Out[75]:
year name points penalty
one 2014 Elise 1.5 NaN
two 2015 Julia 1.7 NaN
three 2016 Jhon 3.6 NaN
four 2017 Charles 2.5 NaN
five 2018 Charles 2.9 NaN

컬럼값 새로 지정하기

데이타프레임이름[컬럼명]=[값1, 값2 ... ]
In [76]:
df['penalty'] = [1,4,2,2,1]
df
Out[76]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 4
three 2016 Jhon 3.6 2
four 2017 Charles 2.5 2
five 2018 Charles 2.9 1

컬럼 추가하기 2

데이타프레임이름[새로운컬럼명] = [값1, 값2 ....]
In [77]:
df['Gender'] = ['Female', 'Female', 'Male', 'Male', 'Male']
df
Out[77]:
year name points penalty Gender
one 2014 Elise 1.5 1 Female
two 2015 Julia 1.7 4 Female
three 2016 Jhon 3.6 2 Male
four 2017 Charles 2.5 2 Male
five 2018 Charles 2.9 1 Male

데이타프레임의 컬럼 이름 변경하기

데이타프레임명.columns = [컬럼값1, 컬럼값2 ...]
In [80]:
df.columns = ['년도', '이름', '포인트', '페널티', '성별']
df
Out[80]:
년도 이름 포인트 페널티 성별
one 2014 Elise 1.5 1 Female
two 2015 Julia 1.7 4 Female
three 2016 Jhon 3.6 2 Male
four 2017 Charles 2.5 2 Male
five 2018 Charles 2.9 1 Male

Dataframe 정보 알아보기

  • 데이타프레임이름.describe()
  • 총합, 평균, 표준편차,최소값을 자동으로 출력
In [67]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
df = pd.DataFrame(data)
In [68]:
df.describe()
Out[68]:
year points
count 5.000000 5.00000
mean 2016.000000 2.44000
std 1.581139 0.86487
min 2014.000000 1.50000
25% 2015.000000 1.70000
50% 2016.000000 2.50000
75% 2017.000000 2.90000
max 2018.000000 3.60000

Dataframe 컬럼 필터링

  • df[컬럼명] : 한개의 컬럼만 추출
  • df.컬럼명 : 한개의 컬럼만 추출
  • 컬럼 추출시 시리즈(Series) 표시
  • 다중필터링: 여러개의 컬럼을 필터링시에는 겹대괄호 이용 [[ ... ]]
        df[[컬럼명1, 컬럼명2…]]
In [93]:
data = {"name":["Haidi", "Haidi", "Haidi", "Charles", "Charles"],
       "year":[2014, 2015, 2016, 2015, 2017],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
df = pd.DataFrame(data, columns=["year", "name", "points"], 
                    index=["one", "two", "three", "four", "five"])
df
Out[93]:
year name points
one 2014 Haidi 1.5
two 2015 Haidi 1.7
three 2016 Haidi 3.6
four 2015 Charles 2.5
five 2017 Charles 2.9

1개의 컬럼만 추출

In [40]:
df["year"]
Out[40]:
one      2014
two      2015
three    2016
four     2015
five     2017
Name: year, dtype: int64
In [41]:
df.year
Out[41]:
one      2014
two      2015
three    2016
four     2015
five     2017
Name: year, dtype: int64
In [94]:
# 추출된 컬럼은 시리즈 
type(df.year)
Out[94]:
pandas.core.series.Series

여러개의 컬럼추출시에는 [[ 와 ]] 이용

In [95]:
df[["year","points"]]
Out[95]:
year points
one 2014 1.5
two 2015 1.7
three 2016 3.6
four 2015 2.5
five 2017 2.9

Dataframe 열에 초기값 입력하기

  • df[컬럼명] = 값 : 같은값으로 초기화
  • df[컬럼명] = [값1, 값2 ... ] : 리스트형태로 나열
In [96]:
data = {'Math':[100, 45, 89, 40],
       'Eng':[80, 95, 88, 77],
       'Sci':[100, 77, 89, 100]}

df = pd.DataFrame(data, index=['Jullia', 'Maria', 'Jhon', 'Tom'])

새로운 컬럼 추가후 초기값을 동일하게 지정

데이타프레임이름[컬럼명] = 값
In [47]:
df['kor'] = 50
df
Out[47]:
Eng Math Sci kor
Jullia 80 100 100 50
Maria 95 45 77 50
Jhon 88 89 89 50
Tom 77 40 100 50

새로운 컬럼 추가후 초기값이 서로 다른 경우 : 리스트 이용

In [48]:
df['Music'] = [100, 45, 60, 79]
df
Out[48]:
Eng Math Sci kor Music
Jullia 80 100 100 50 100
Maria 95 45 77 50 45
Jhon 88 89 89 50 60
Tom 77 40 100 50 79

Dataframe 열 추가와 증가값 지정

  • df[컬럼명] = np.arrange(최종숫자)
In [99]:
data = {"name":["Haidi", "Haidi", "Haidi", "Charles", "Charles"],
       "year":[2014, 2015, 2016, 2015, 2017],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9]}
df = pd.DataFrame(data, columns=["year", "name", "points", "penalty"], 
                    index=["one", "two", "three", "four", "five"])
In [101]:
df
Out[101]:
year name points penalty
one 2014 Haidi 1.5 NaN
two 2015 Haidi 1.7 NaN
three 2016 Haidi 3.6 NaN
four 2015 Charles 2.5 NaN
five 2017 Charles 2.9 NaN
In [102]:
df["penalty"] = np.arange(11,16)
df
Out[102]:
year name points penalty
one 2014 Haidi 1.5 11
two 2015 Haidi 1.7 12
three 2016 Haidi 3.6 13
four 2015 Charles 2.5 14
five 2017 Charles 2.9 15

Series 이용해서 DataFrame에 컬럼 추가하기

  • 시리즈(Series) 생성시 행의 index 이름값 사용
  • 생성된 시리즈를 컬럼 추가시 사용
In [104]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9],
       "penalty": np.arange(1,6)}
df = pd.DataFrame(data, columns=["year","name","points","penalty"],
                 index=["one", "two", "three", "four", "five"])
df
Out[104]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5

시리즈 생성하기

indxe 명은 데이타프레임의 인덱스로 구성되어 있는지 확인
In [106]:
s = pd.Series([-1.2, -1.5, -1.7], index=["two", "four", "five"])
s
Out[106]:
two    -1.2
four   -1.5
five   -1.7
dtype: float64

Series를 데이타프레임의 새컬럼에 추가하기


In [107]:
df["debt"] = s
df
Out[107]:
year name points penalty debt
one 2014 Elise 1.5 1 NaN
two 2015 Julia 1.7 2 -1.2
three 2016 Jhon 3.6 3 NaN
four 2017 Charles 2.5 4 -1.5
five 2018 Charles 2.9 5 -1.7

Dataframe 기존 열의 값 이용하여 새로운 열 추가하기

  • df[컬럼명] = df[컬럼1] - df[컬럼2]
  • df[컬럼명] = df[컬럼]을 이용한 비교연산자
In [56]:
df
Out[56]:
year name points penalty debt
one 2014 Elise 1.5 1 NaN
two 2015 Julia 1.7 2 -1.2
three 2016 Jhon 3.6 3 NaN
four 2017 Charles 2.5 4 -1.5
five 2018 Charles 2.9 5 -1.7

기존 컬럼의 값에 연산을 적용해서 새로운 컬럼 추가

In [108]:
df["net_points"] = df["points"]-df["penalty"]
df
Out[108]:
year name points penalty debt net_points
one 2014 Elise 1.5 1 NaN 0.5
two 2015 Julia 1.7 2 -1.2 -0.3
three 2016 Jhon 3.6 3 NaN 0.6
four 2017 Charles 2.5 4 -1.5 -1.5
five 2018 Charles 2.9 5 -1.7 -2.1

기존 컬럼을 이용하여 조건식 생성하기 => 새로운 컬럼 추가

In [58]:
df["high_points"] = df["net_points"] > 0
df
Out[58]:
year name points penalty debt net_points high_points
one 2014 Elise 1.5 1 NaN 0.5 True
two 2015 Julia 1.7 2 -1.2 -0.3 False
three 2016 Jhon 3.6 3 NaN 0.6 True
four 2017 Charles 2.5 4 -1.5 -1.5 False
five 2018 Charles 2.9 5 -1.7 -2.1 False

퀴즈

아래와 같은 형태로 데이타프레임을 생성하고 총합과 평균을 출력한다. 평균값이 70보다 크면 True를 출력한다.


Math    Eng Sci Kor  Music  Total    Avg    Pass
Jullia  100 80  100   50    100 430    86.0 True
Maria   45  95  77    50    45  312    62.4 False
Jhon    89  88  89    50    60  376    75.2 True
Tom     40  77  100   50    79  346    69.2 False
In [126]:
data = {'Math':[100, 45, 89, 40],
       'Eng':[80, 95, 88, 77],
       'Sci':[100, 77, 89, 100],
       'Kor':[50, 50, 50, 50 ],
        'Music':[100, 45, 60, 79]}

df = pd.DataFrame(data, index=['Jullia', 'Maria', 'Jhon', 'Tom'])
df
Out[126]:
Math Eng Sci Kor Music
Jullia 100 80 100 50 100
Maria 45 95 77 50 45
Jhon 89 88 89 50 60
Tom 40 77 100 50 79
In [127]:
df['Total'] = df['Math']+df['Eng']+df['Sci']+df['Kor']+df['Music']
In [128]:
df['Avg'] = df['Total']/ 5
df['Pass'] = df['Avg'] > 70
df
Out[128]:
Math Eng Sci Kor Music Total Avg Pass
Jullia 100 80 100 50 100 430 86.0 True
Maria 45 95 77 50 45 312 62.4 False
Jhon 89 88 89 50 60 376 75.2 True
Tom 40 77 100 50 79 346 69.2 False

Dataframe : 열 삭제

  • del df[컬럼명]
In [144]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9],
       "penalty": np.arange(1,6)}
df = pd.DataFrame(data, columns=["year","name","points","penalty"],
                 index=["one", "two", "three", "four", "five"])
In [145]:
del df["penalty"]
df
Out[145]:
year name points
one 2014 Elise 1.5
two 2015 Julia 1.7
three 2016 Jhon 3.6
four 2017 Charles 2.5
five 2018 Charles 2.9

Dataframe : 행 추출

  • 데이타프레임이름[start:end]
  • 인덱스는 행 이름이나 숫자로 가능
In [151]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9],
       "penalty": np.arange(1,6)}
df = pd.DataFrame(data, columns=["year","name","points","penalty"],
                 index=["one", "two", "three", "four", "five"])
df
Out[151]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5

컬럼 슬라이싱

  • 데이타프레임이름[컬럼명]
  • 데이타프레임이름[[컬럼명1, 컬럼명2 ...]]
In [154]:
df[['year','name']]
Out[154]:
year name
one 2014 Elise
two 2015 Julia
three 2016 Jhon
four 2017 Charles
five 2018 Charles

행 슬라이싱 1

  • 데이타프레임[시작인덱스:끝인덱스]
In [70]:
df[0:3]
Out[70]:
Info year name points penalty
Order
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3

행 슬라이싱 2

  • 데이타프레임[시작인덱스명:끝인덱스명]
In [71]:
df["two":"four"]
Out[71]:
Info year name points penalty
Order
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4

Dataframe : 행슬라이싱. loc 이용

  • 데이타프레임이름.loc[인덱스명] => 1개
  • 데이타프레임이름.loc[start인덱스명:end인덱스명] => 다중
  • 인덱스는 행 이름으로 가능
In [175]:
df
Out[175]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5
In [176]:
df.loc["two"]
Out[176]:
year        2015
name       Julia
points       1.7
penalty        2
Name: two, dtype: object
In [177]:
df.loc["two":"four"]
Out[177]:
year name points penalty
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4

Dataframe : 특정 행의 특정 열 추출. loc 이용

  • df.loc[행인덱스start:행인덱스end, 컬럼명]
  • 데이타프레임에서 start와 end-1까지의 행 추출시 컬럼 값만 추출
  • 데이타프레임이름.loc[ : , [컬럼명1, 컬럼명2] ]
  • 데이타프레임이름.loc[행인덱스1:행인덱스2, [컬럼명1, 컬럼명2] ]
In [178]:
data = {"name":['Elise', 'Julia', 'Jhon', 'Charles', 'Charles'],
       "year":[2014, 2015, 2016, 2017, 2018],
       "points":[1.5, 1.7, 3.6, 2.5, 2.9],
       "penalty": np.arange(1,6)}
df2 = pd.DataFrame(data, columns=["year","name","points","penalty"],
                 index=["one", "two", "three", "four", "five"])
df2
Out[178]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5

범위를 지정한 행의 특정 컬럼값

데이타프레임이름.loc[행인덱스start:행인덱스end, 컬럼명]
In [179]:
df2.loc["two":"four","points"]
Out[179]:
two      1.7
three    3.6
four     2.5
Name: points, dtype: float64

모든 행에서 특정 컬럼의 값 표시

데이타프레임이름.loc[ : , 컬럼명 ]

In [181]:
df2.loc[:, "year"]
Out[181]:
one      2014
two      2015
three    2016
four     2017
five     2018
Name: year, dtype: int64

전체 데이타프레임

데이타프레임이름.loc[ : , : ]

In [183]:
df2.loc[:,:]
Out[183]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5

특정 행 값 표시

데이타프레임이름.loc[행이름 , : ]

In [184]:
df2.loc['one', :]
Out[184]:
year        2014
name       Elise
points       1.5
penalty        1
Name: one, dtype: object

다중 컬럼값 추출

데이타프레임이름.loc[ : , [컬럼명1, 컬럼명2] ]

In [185]:
df2.loc[:, ["year","name"]]
Out[185]:
year name
one 2014 Elise
two 2015 Julia
three 2016 Jhon
four 2017 Charles
five 2018 Charles

연속된 행의 연속된 컬럼 표시

데이타프레임이름.loc[ 인덱스명Start:인덱스명End , 컬럼명Start:컬럼명End ]

In [187]:
df2.loc["three":"five","year":"points"]
Out[187]:
year name points
three 2016 Jhon 3.6
four 2017 Charles 2.5
five 2018 Charles 2.9

Dataframe : loc 이용. 행 추가

  • 데이타프레임이름.loc [ 행인덱스명, : ] = [값1, 값2 ...]
In [188]:
df2
Out[188]:
year name points penalty
one 2014 Elise 1.5 1
two 2015 Julia 1.7 2
three 2016 Jhon 3.6 3
four 2017 Charles 2.5 4
five 2018 Charles 2.9 5
In [189]:
df2.loc['six',:] = [2019, "hayoung", 4.0, 6]
df2
Out[189]:
year name points penalty
one 2014.0 Elise 1.5 1.0
two 2015.0 Julia 1.7 2.0
three 2016.0 Jhon 3.6 3.0
four 2017.0 Charles 2.5 4.0
five 2018.0 Charles 2.9 5.0
six 2019.0 hayoung 4.0 6.0

Dataframe : loc 이용. 열 추가

  • 데이타프레임이름.loc [ :, 열인덱스명 ] = [값1, 값2 ...]
In [190]:
df2.loc[:,'bonus']=[10,20,30,40,50,60]
df2
Out[190]:
year name points penalty bonus
one 2014.0 Elise 1.5 1.0 10
two 2015.0 Julia 1.7 2.0 20
three 2016.0 Jhon 3.6 3.0 30
four 2017.0 Charles 2.5 4.0 40
five 2018.0 Charles 2.9 5.0 50
six 2019.0 hayoung 4.0 6.0 60

Dataframe : iloc 이용. 행추출

  • 데이타프레임이름.iloc[인덱스번호] : 시리즈형태로 세로로 추출
In [192]:
df2
Out[192]:
year name points penalty bonus
one 2014.0 Elise 1.5 1.0 10
two 2015.0 Julia 1.7 2.0 20
three 2016.0 Jhon 3.6 3.0 30
four 2017.0 Charles 2.5 4.0 40
five 2018.0 Charles 2.9 5.0 50
six 2019.0 hayoung 4.0 6.0 60
In [193]:
df.iloc[0]
Out[193]:
year        2014
name       Elise
points       1.5
penalty        1
Name: one, dtype: object

Dataframe : iloc 이용. 행, 컬럼 범위 추출

  • 데이타프레임이름. iloc[ 인덱스start:인덱스end, 컬럼Start:컬럼End]
  • 데이타프레임이름.iloc[ [인덱스 숫자], [컬럼인덱스 숫자 ]]
  • 데이타프레임이름.iloc[ [인덱스숫자1,인덱스숫자2 ..], [컬럼인덱스숫자1, 컬럼인덱스숫자2 ... ]]
In [194]:
df2
Out[194]:
year name points penalty bonus
one 2014.0 Elise 1.5 1.0 10
two 2015.0 Julia 1.7 2.0 20
three 2016.0 Jhon 3.6 3.0 30
four 2017.0 Charles 2.5 4.0 40
five 2018.0 Charles 2.9 5.0 50
six 2019.0 hayoung 4.0 6.0 60

연속된 행과 컬럼 추출

  • 데이타프레임이름. iloc[ 인덱스start:인덱스end, 컬럼Start:컬럼End]
In [196]:
df2.iloc[0:2, 0:2]
Out[196]:
year name
one 2014.0 Elise
two 2015.0 Julia

비연속적인 행과 컬럼 추출 : 겹대괄호 이용

데이타프레임이름.iloc[ [인덱스숫자1,인덱스숫자2 ..],
              [컬럼인덱스숫자1, 컬럼인덱스숫자2 ... ]]
In [197]:
df2.iloc[[0,1,3], [1,2]]
Out[197]:
name points
one Elise 1.5
two Julia 1.7
four Charles 2.5
In [198]:
df2.iloc[:, 1:4]
Out[198]:
name points penalty
one Elise 1.5 1.0
two Julia 1.7 2.0
three Jhon 3.6 3.0
four Charles 2.5 4.0
five Charles 2.9 5.0
six hayoung 4.0 6.0

넘파이 2차원 배열을 이용하여 데이타프레임 만들기

In [218]:
dfTest = pd.DataFrame(np.random.randint(1,100,size=30).reshape(-1,5),
                     columns=['col1','col2','col3', 'col4', 'col5'],
                     index =['row1','row2','row3', 'row4', 'row5', 'row6'])
dfTest
Out[218]:
col1 col2 col3 col4 col5
row1 17 64 82 61 69
row2 59 78 47 74 93
row3 92 48 72 30 22
row4 26 80 5 27 73
row5 56 66 38 99 93
row6 49 21 32 91 10

퀴즈 : iloc / loc 이용

1) row1 행만 표시 
2) row2~row4까지 표시 
3) col5 컬럼만 표시 
4) row1 행중에서 col2,col5 표시 
5) row5,6 행 중에서 col3만 표시
In [231]:
dfTest.iloc[0,:]
Out[231]:
col1    17
col2    64
col3    82
col4    61
col5    69
Name: row1, dtype: int32
In [232]:
dfTest.iloc[1:4,:]
Out[232]:
col1 col2 col3 col4 col5
row2 59 78 47 74 93
row3 92 48 72 30 22
row4 26 80 5 27 73
In [233]:
dfTest.iloc[:,4]
Out[233]:
row1    69
row2    93
row3    22
row4    73
row5    93
row6    10
Name: col5, dtype: int32
In [234]:
dfTest.iloc[0,[1,4]]
Out[234]:
col2    64
col5    69
Name: row1, dtype: int32
In [235]:
dfTest.iloc[[4,5],2]
Out[235]:
row5    38
row6    32
Name: col3, dtype: int32
In [236]:
dfTest.iloc[4:6,2]
Out[236]:
row5    38
row6    32
Name: col3, dtype: int32

행과 열 삭제하기


- 데이타프레임명.drop([행이름1, 행이름2 ... ])
- 데이타프레임명.drop([열이름1, 열이름2 ... ], axis=1 )
- 데이타프레임명.drop(index=[행이름1, 행이름2 ...], 
                        columns=[열이름1, 열이름2 ... ])
- 원본 데이타프레임에는 실제로 삭제되지 않는다. 
- 원본 데이타프레임에서도 삭제되길 원한다면 
      inplace=True 옵션을 추가해야한다.

                        `
In [259]:
dfTest2 = pd.DataFrame(np.random.randint(1,100,size=30).reshape(-1,5),
                     columns=['col1','col2','col3', 'col4', 'col5'],
                     index =['row1','row2','row3', 'row4', 'row5', 'row6'])
dfTest2
Out[259]:
col1 col2 col3 col4 col5
row1 16 90 72 18 8
row2 33 57 71 11 47
row3 87 93 18 36 14
row4 99 14 54 98 29
row5 40 93 10 26 36
row6 48 24 29 87 31

특정 컬럼 삭제

In [260]:
# inplace=True 원본에도 삭제 적용

dfTest2.drop(columns = ['col5'], inplace=True)
In [261]:
dfTest2
Out[261]:
col1 col2 col3 col4
row1 16 90 72 18
row2 33 57 71 11
row3 87 93 18 36
row4 99 14 54 98
row5 40 93 10 26
row6 48 24 29 87

특정 행 삭제

In [262]:
dfTest2.drop(index=['row1'], inplace=True)
dfTest2
Out[262]:
col1 col2 col3 col4
row2 33 57 71 11
row3 87 93 18 36
row4 99 14 54 98
row5 40 93 10 26
row6 48 24 29 87
In [264]:
dfTest2.drop(index=['row5'], columns = ['col4'], inplace=True)
In [265]:
dfTest2
Out[265]:
col1 col2 col3
row2 33 57 71
row3 87 93 18
row4 99 14 54
row6 48 24 29
반응형

'Python > Pandas' 카테고리의 다른 글

Pandas_06. 타이타닉  (0) 2019.08.26
Pandas_05  (0) 2019.08.11
Pandas_04  (0) 2019.08.11
Pandas_03  (0) 2019.08.11
Pandas_01  (0) 2019.08.11