[TIL] 21.05.07 dataframe 조작

Seung Joo·2021년 5월 14일
0

TIL

목록 보기
2/31
post-thumbnail

NaN은 프로그래밍 설계상 Float type임

1. Read_csv

read_csv_docs
read_csv의 names 매개변수로 column추가

df = pd.read_csv(.csv or url, names=headers)
df.head()

2. DataFrame.apply()

apply() 함수
내가 만든 함수의 내용을 일괄적용 가능

# int 형변환 함수
def to_int(string):
    return int(string.replace(',', ''))

df_cp = df.copy() # copy본 생성
df_cp['column'] = (df_cp['column'].apply(to_int))

2.2 apply 활용하여 특정 컬럼 변환

# string to int & float 함수
def str_to_num(string):
    try:
        if '.' in string:
            if ',' in string:
                return float(string.replace(',' , ''))
            else:
                return float(string)
        else:
            if ',' in string:
                return int(string.replace(',' , ''))
            else:
                return int(string)
    except:
        return string
# column 정보 가져와서 필요없는 column 제거
col = df.columns
col = col.drop('except_col')
col
# 변환하고자 하는 컬럼 대입하여 형변환
for c in col:
    df['col'] = df['col'].apply(str_to_num)

3. ❗ 얕은 복사, 깊은 복사 ❗


df_cp = df를 한 후에, df_cp를 작업하면 메모리 주소만 할당된 얕은 복사이기 때문에 df원본에도 영향을 미치게 된다.

pandas.DataFrame.copy를 사용하면 된다.

pandas.DataFrame.copy새로운 메모리를 할당하여 똑같은 복사본을 만들기 때문에 원본 데이터에 영향을 주지 않는다.
(deep 파라미터의 기본값은 True이기 때문에 기본적으로 깊은복사가 된다.)

✅SettingWithCopyWarning

경고 메시지에 대한 정리된 내용 참고 포스트
pd.options.mode.chained_assignment = None
을 활용하여 경고 메시지를 지울 수도 있다.

4. astype, pd.numeric으로 형변환

df['col'] = ['col'].apply(pd.to_numeric) # 숫자형으로 변환
# .astype(float)으로도 변환 가능

astype, pd.numeric 참고 포스트

profile
조금씩 천천히

0개의 댓글