본문 바로가기
SK 행복성장캠퍼스/Pandas

20-10-07, Pandas_2일차(행렬검색, index)

by NickNuma 2020. 10. 12.

2일차에서는 1일차에서 했던 행열 검색 및 입력을 잠깐 알아보고
index, 행, 열 추가 삭제, 정렬, NaN처리, 유용한 함수들에 대해서 살펴봤습니다.


DataFrame 행/열 검색

"""
    DataFrame 행 검색
    1) loc 함수   : index name
        ==> loc[인덱스 라벨]

    2) iloc 함수  : index location
        ==> iloc[인덱스 위치] : 0부터

    *행과 열 조합
        df.loc[행, 열]    ==> 인덱스 라벨 및 컬럼명 사용
        -인덱싱, fancy, boolean, 슬라이싱 모드 가능

        df.iloc[행, 열]   ==> 인덱스 위치 및 컬럼 위치 사용
        -인덱싱, fancy, boolean, 슬라이싱 모드 가능
        .iloc requires numeric indexers, got ['a' 'b']

    * loc 함수 또는 iloc 함수 사용한 색인값을 이용하여 값 변경이 가능하다.
        df.loc[행, 열] = 값
        df.iloc[행, 열] = 값

"""
print("2. 변경 전 데이터 : ", df.loc[10, 'c'])    # 2     
print(df.iloc[0, 2])    # 2                         
df.loc[10, 'c'] = 100                             
print("3. 변경 후 데이터 : ", df.loc[10, 'c'])    # 100 
print("4. 변경 전 데이터 : \n", df.loc[ [10,20], ['a', 'b'] ])
#      a  b
# 10  4  6
# 20  6  3
df.loc[[10,20], ['a', 'b']] = -100
print("5. 변경 후 데이터 : \n", df)
#       a    b    c   d   e
# 10 -100 -100  100  12  25
# 20 -100 -100    3  23  34
# 30    7    2    4  64  42
# 40    7    2    1  41  15
# 50    5   55    2  28  52
print("6. 변경 전 데이터 : \n", df.iloc[ [3,4], -1 ])
# 40    15
# 50    52
# Name: e, dtype: int64
df.iloc[ [3,4], -1 ]    = 1000
print("7. 변경 후 데이터 : \n", df)
#      a    b    c   d     e
# 10 -100 -100  100  12    25
# 20 -100 -100    3  23    34
# 30    7    2    4  64    42
# 40    7    2    1  41  1000
# 50    5   55    2  28  1000

 


DataFrame 인덱스 생성

"""
    DataFrame의 인덱스 생성 방법
    1. 자동 생성
    2. 명시적 생성
    3. Int64Index 설정 ==> np.arange(정수)
    4. Float64Index 설정 ==> np.arange(실수)
    5. IntervalIndex 설정 ==> pd.IntervalIndex.from_breaks(범위 리스트)
    6. DatetimeIndex 설정 (**)    
"""

1. index 자동생성

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]})
print("1. 자동 생성 방법 :\n", df)
#    a  b
# 0  4  6
# 1  6  3
# 2  7  2

2. index 명시적 지정

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]},
    index = list('xyz'))
print("2. 명시적 지정 방법 :\n", df, list('xyz'))
# 2. 명시적 지정 방법 :
#     a  b
# x  4  6
# y  6  3
# z  7  2 ['x', 'y', 'z']

3. numpy를 이용한 index 생성 (Int64)

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]},
    index = np.arange(10, 13))
print("3. np.arange (Int64Index) :\n", df, np.arange(3), df.index)
#     a  b
# 10  4  6
# 11  6  3
# 12  7  2 [0 1 2] Int64Index([10, 11, 12], dtype='int64')

4. numpy를 이용한 index 생성 (Float64)

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]},
    index = np.arange(10.0, 13.0))
print("4. np.arange (Float64Index) :\n", df, df.index)
#       a  b
# 10.0  4  6
# 11.0  6  3
# 12.0  7  2 Float64Index([10.0, 11.0, 12.0], dtype='float64')

5. pandas를 이용한 index 생성 (범위 리스트)

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]},
    index = pd.IntervalIndex.from_breaks([0, 0.5, 1.0, 1.5]))
print("5. pd.IntervalIndex.from_breaks (IntervalIndex) :\n", df, df.index)
#             a  b
# (0.0, 0.5]  4  6
# (0.5, 1.0]  6  3
# (1.0, 1.5]  7  2 IntervalIndex([(0.0, 0.5], (0.5, 1.0], (1.0, 1.5]],
#               closed='right',
#               dtype='interval[float64]')

 


DatetimeIndex (날짜/시간)

1. 기본 DatetimeIndex Frame

    가. 일자/월/년도

date = pd.date_range(start="01/01/2000", end="01/20/2000")
print(date)
# DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
#                '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
#                '2000-01-09', '2000-01-10', '2000-01-11', '2000-01-12',
#                '2000-01-13', '2000-01-14', '2000-01-15', '2000-01-16',
#                '2000-01-17', '2000-01-18', '2000-01-19', '2000-01-20'],
#               dtype='datetime64[ns]', freq='D')

    나. 년도/월/일자

date = pd.date_range(start="2000/01/01", end="2000/01/20")
print(date)
# DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
#                '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
#                '2000-01-09', '2000-01-10', '2000-01-11', '2000-01-12',
#                '2000-01-13', '2000-01-14', '2000-01-15', '2000-01-16',
#                '2000-01-17', '2000-01-18', '2000-01-19', '2000-01-20'],
#               dtype='datetime64[ns]', freq='D')

2. 일자 변경 ( periods =  (Default = 일자 변경) )

date = pd.date_range("2020/01/01", periods=8)
print("일자 변경, periods: \n", date)
# 일자 변경, periods:
#  DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
#                '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08'],
#               dtype='datetime64[ns]', freq='D')

3. 월 변경 ( periods = , freq = 'M")

date = pd.date_range("2020/01/01", periods=8, freq='M')
print("월 변경, periods, freq='M': \n", date)
# 월 변경, periods, freq='M':
#  DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30',
#                '2020-05-31', '2020-06-30', '2020-07-31', '2020-08-31'],
#               dtype='datetime64[ns]', freq='M')

4. 시간 변경 ( periods = , freq = 'H")

date = pd.date_range("2020/01/01", periods=8, freq='H')
print("시간 변경, periods, freq='H': \n", date)
# 변경, periods, freq = 'H':
# DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 01:00:00',
#                '2020-01-01 02:00:00', '2020-01-01 03:00:00',
#                '2020-01-01 04:00:00', '2020-01-01 05:00:00',
#                '2020-01-01 06:00:00', '2020-01-01 07:00:00'],
#               dtype='datetime64[ns]', freq='H')

5. 년도 변경 ( periods = , freq = 'A")

date = pd.date_range("2020/01/01", periods=8, freq='A')
print("년도 변경, periods, freq='A': \n", date)
# 년도 변경, periods, freq='A':
#  DatetimeIndex(['2020-12-31', '2021-12-31', '2022-12-31', '2023-12-31',
#                '2024-12-31', '2025-12-31', '2026-12-31', '2027-12-31'],
#               dtype='datetime64[ns]', freq='A-DEC')

pandas.date_range()를 이용해 index 생성

date = pd.date_range("2020/01/01", periods=10)
df = pd.DataFrame({"num":range(10)}, index=date)
print(df)
#             num
# 2020-01-01    0
# 2020-01-02    1
# 2020-01-03    2
# 2020-01-04    3
# 2020-01-05    4
# 2020-01-06    5
# 2020-01-07    6
# 2020-01-08    7
# 2020-01-09    8
# 2020-01-10    9

 


원본 DataFrame

df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2],
    'key':list('ABC')})
print("1. 원본: \n", df)
#    a  b key
# 0  4  6   A
# 1  6  3   B
# 2  7  2   C

set_index: 기존 column을 index로 변경 (1, 복사본)

#1. 기존 column을 index로 변경 (복사본 생성): set_index(column)
df2 = df.set_index('key')
print("2. 기존 column을 index로 변경(복사본 생성) : \n", df2)
#      a  b
# key
# A    4  6
# B    6  3
# C    7  2

set_index: 기존 column을 index로 변경 (2, 자신이 변경 inplace = True)

#2. 기존 column을 index로 변경 (자신이 변경): set_index(column, inplace=True)
df.set_index('key', inplace=True)
print("2. set_index(column, inplace=True) (자신이 변경) : \n", df)
#      a  b
# key
# A    4  6
# B    6  3
# C    7  2

reset_index: 새로운 자동 index 추가

#3. 새로운 인덱스로 변경 (복사본) ==> reset_index()
df2 = df.reset_index()  # 기존 인덱스를 컬럼으로 변경하고 새로운 인덱스 설정
print("3. 기존 index를 column으로 변경(복사본 생성) : \n", df2)
#    key  a  b
# 0   A  4  6
# 1   B  6  3
# 2   C  7  2

reset_index: 기존 index를 삭제(drop=True)하고 새로운 index 설정

#3. df.reset_index(drop=True, inplace=True)
df.reset_index(drop=True, inplace=True) #기존 인덱스를 삭제하고 새로운 인덱스 설정
print("4. df.reset_index(inplace=True) (자신이 변경) : \n", df)
#    a  b
# 0  4  6
# 1  6  3
# 2  7  2

기존 index 순서 변경 : reindex(index = 리스트값) 

1. 원본

#4. reindex(index=리스트값) ==> 기존 인덱스 순서 변경
df = pd.DataFrame({
    'a' : [4,6,7],
    'b' : [6,3,2]},
    index =list('BAC'))
print("4.원본: \n", df)
#    a  b
# B  4  6
# A  6  3
# C  7  2
print("="*100)

2. reindex (인덱스 순서 변경)

df = df.reindex(index = ['A', 'B', 'C'])
print("4. reindex: \n", df)
#    a  b
# A  6  3
# B  4  6
# C  7  2

3. reindex로 기존에 없던 인덱스를 지정하면, 요소값 = NaN

df = df.reindex(index = ['A', 'B', 'C2'])
print("4. reindex, 기존에 없던 인덱스 지정 : (NaN값 반환) \n", df)
#      a    b
# A   6.0  3.0
# B   4.0  6.0
# C2  NaN  NaN

concat (DataFrame 병합)

df = pd.DataFrame({
        'a' : [4,6,7]},
        index=[1,2,3])

df2 = pd.DataFrame({
        'a' : [40,60,70]},
        index=[1,2,3])

new_df = pd.concat([df, df2])
print("6. 병합:\n", new_df)
#     a
# 1   4
# 2   6
# 3   7
# 1  40
# 2  60
# 3  70

0~끝까지 인덱스 새로 병합, ignore_index=True

new_df = pd.concat([df, df2], ignore_index=True)
print("6. 병합 (ignore_index=True) :\n", new_df)
#     a
# 0   4
# 1   6
# 2   7
# 3  40
# 4  60
# 5  70

x축 기준으로 병합 (axis=0)

new_df = pd.concat([df, df2], axis=0)
print("x축 기준으로 포개기 :\n", new_df)
#     a
# 1   4
# 2   6
# 3   7
# 1  40
# 2  60
# 3  70

y축 기준으로 병합 (axis=1)

new_df = pd.concat([df, df2], axis=1)
print("y축 기준으로 나열하기 :\n", new_df)
#    a   a
# 1  4  40
# 2  6  60
# 3  7  70
반응형

'SK 행복성장캠퍼스 > Pandas' 카테고리의 다른 글

20-10-06, Pandas_1일차  (0) 2020.10.07

댓글