Notice
Recent Posts
Recent Comments
Link
아미(아름다운미소)
pandas 여러열적용 본문
df[cols] = df[cols].astype(float).fillna(0).astype(int)
cols = ['A', 'B', 'C', 'D'] # 변환하고 싶은 열 이름들
for col in cols:
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0).astype(int)
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce').fillna(0).astype(int)
예제
import pandas as pd
# 샘플 데이터프레임 생성
data = {
'A': ['1', '2', '3', '4', ''],
'B': ['5', '6', '7', '8', 'abc'],
'C': ['9', '10', '11', '12', ''],
'D': ['13', '14', '15', '16', 'def']
}
df = pd.DataFrame(data)
print(df)
A B C D
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
4 abc def
cols = ['A', 'B', 'C', 'D']
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce').fillna(0).astype(int)
print(df)
A B C D
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
4 0 0 0 0
'랭귀지 > pandas' 카테고리의 다른 글
pandas dataframe 컬럼비교 (0) | 2024.07.18 |
---|---|
pandas filter (0) | 2024.07.17 |
pandas 조건 (0) | 2024.07.16 |
pandas 빈데이타프레임처리 (0) | 2024.07.15 |
pandas to_numeric (1) | 2024.07.15 |
Comments