Notice
Recent Posts
Recent Comments
Link
아미(아름다운미소)
pandas to_numeric 본문
여러컬럼
import pandas as pd
df = pd.DataFrame({
'A': ['a', 'a', 'b', 'b', 'c', 'c','x'],
'B': ['x', 'y', 'x', 'y', 'x', 'y','y'],
'C': [10.5, '20', 30.2, 'aaa', '50.1', '60',None],
'D': [1.0, '2', 3.2, 'bbb', 5.1, '6',None]
})
numeric_cols = ['C', 'D']
#방법1
df = df.assign(**{col: pd.to_numeric(df[col], errors='coerce').fillna(0).astype(int) for col in numeric_cols})
#방법2
df[numeric_cols] = df[numeric_cols].apply(lambda col: pd.to_numeric(col, errors='coerce').fillna(0).astype(int))
grouped = df.groupby(['A', 'B'])
result = grouped[numeric_cols].sum().reset_index()
print(result)
컬럼하나
import pandas as pd
df = pd.DataFrame({
'A': ['a', 'a', 'b', 'b', 'c', 'c','x'],
'B': ['x', 'y', 'x', 'y', 'x', 'y','y'],
'C': ['10.5', '20', 30.2, 'aaa', 50.1, '60',None]
})
df['A'] = df['A'].astype(str)
df['B'] = df['B'].astype(str)
df['C'] = pd.to_numeric(df['C'], errors='coerce').fillna(0).astype(int)
grouped = df.groupby(['A', 'B'])
result = grouped['C'].sum().reset_index()
print(result)
'랭귀지 > pandas' 카테고리의 다른 글
pandas 조건 (0) | 2024.07.16 |
---|---|
pandas 빈데이타프레임처리 (0) | 2024.07.15 |
groupby 문자열포함 sum (0) | 2024.07.14 |
pandas concat option (0) | 2024.07.13 |
pandas concat (0) | 2024.07.13 |
Comments