Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- PyQt
- Excel
- node.js
- 리눅스
- 함수
- 라즈베리파이
- Unity
- 다이어트
- pandas
- 맛집
- ASP
- swift
- urllib
- GIT
- ubuntu
- MS-SQL
- Linux
- PyQt5
- mssql
- tensorflow
- port
- python
- flutter
- IOS
- javascript
- MySQL
- PER
- 날짜
- 유니티
- sqlite
Archives
아미(아름다운미소)
groupby 문자열포함 sum 본문
Int float 문자 None
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]
})
# A, B 컬럼을 문자열로 변환
df['A'] = df['A'].astype(str)
df['B'] = df['B'].astype(str)
# C 컬럼의 숫자와 문자열 처리
df['C'] = df['C'].apply(lambda x: int(float(x)) if str(x).replace('.', '').isdigit() else 0)
# A, B 컬럼으로 groupby 후 C 컬럼 sum
result = df.groupby(['A', 'B'])['C'].sum().reset_index()
print(result)
예제1
import pandas as pd
df = pd.DataFrame({
'A': ['a', 'a', 'b', 'b', 'c', 'c','a'],
'B': ['x', 'y', 'x', 'y', 'x', 'y','x'],
'C': [10, '', 30, '40', 50, 'ghvuvu',None]
})
# A, B 컬럼을 문자열로 변환
df[['A', 'B']] = df[['A', 'B']].astype(str)
# C 컬럼의 숫자와 문자열, None 처리
# df['C'] = df['C'].apply(lambda x: int(x) if str(x).isdigit() else 0)
df['C'] = df['C'].replace([r'[^0-9]', None, ''], '0', regex=True).astype(int)
# A, B 컬럼으로 groupby 후 C 컬럼 sum
result = df.groupby(['A', 'B'], as_index=False)['C'].sum()
print(result)
예제2
import pandas as pd
df = pd.DataFrame({
'A': ['a', 'a', 'b', 'b', 'c', 'c'],
'B': ['x', 'y', 'x', 'y', 'x', 'y'],
'C': [10, 'aa', 30, '40', 50, '60']
})
# A, B 컬럼을 문자열로 변환
df['A'] = df['A'].astype(str)
df['B'] = df['B'].astype(str)
# C 컬럼의 숫자와 문자열 처리
df['C'] = df['C'].apply(lambda x: int(x) if str(x).isdigit() else 0)
# A, B 컬럼으로 groupby 후 C 컬럼 sum
result = df.groupby(['A', 'B'])['C'].sum().reset_index()
print(result)
예제3
# C 컬럼의 숫자와 문자열 처리
df['C'] = df['C'].apply(lambda x: float(x) if str(x).replace('.', '').isdigit() else 0.0)
# A, B 컬럼으로 groupby 후 C 컬럼 sum
result = df.groupby(['A', 'B'])['C'].sum().reset_index()
print(result)'랭귀지 > pandas' 카테고리의 다른 글
| pandas 빈데이타프레임처리 (0) | 2024.07.15 |
|---|---|
| pandas to_numeric (1) | 2024.07.15 |
| pandas concat option (0) | 2024.07.13 |
| pandas concat (0) | 2024.07.13 |
| pandas groupby sum fillna astype (0) | 2024.07.13 |
Comments
