아래와 같은 학생들의 성적을 나타낸 데이터 프레임이 주어집니다. 아래 지시사항을 따르세요.
인덱스 반 국어성적 수학성적
0 A 100 85
1 B 96 88
2 C 94 91
3 A 92 94
4 B 90 97
5 C 86 100
내가 한 풀이
import pandas as pd
df = pd.DataFrame(
{
"class": ["A", "B", "C", "A", "B", "C"],
"Korean": [100, 96, 94, 92, 90, 86],
"Math": [85, 88, 91, 94, 97, 100],
}
)
korean_sum = df.groupby("class")["Korean"].sum()
print(korean_sum)
print("="*10)
math_sum = df.groupby("class")["Math"].sum()
print(math_sum)
print("="*10)
korean_avg = df.groupby("class")["Korean"].mean()
print(korean_avg)
print("="*10)
math_avg = df.groupby("class")["Math"].mean()
print(math_avg)
다른 사람의 풀이
import pandas as pd
df = pd.DataFrame(
{
"class": ["A", "B", "C", "A", "B", "C"],
"Korean": [100, 96, 94, 92, 90, 86],
"Math": [85, 88, 91, 94, 97, 100],
}
)
grouped = df.groupby("class")
korean_sum = grouped["Korean"].sum()
print(korean_sum)
print("="*10)
math_sum = grouped["Math"].sum()
print(math_sum)
print("="*10)
korean_avg = grouped["Korean"].mean()
print(korean_avg)
print("="*10)
math_avg = grouped["Math"].mean()
print(math_avg)
이렇게 grouped 변수로 묶는것도 추천함
데이터의 구조는 아래와 같습니다. 아래 데이터를 바탕으로 아래 지시사항을 따르세요.
컬럼 명 형식 내용
species object 펭귄의 종
island object 펭귄이 관찰된 섬의 이름
bill_length_mm float64 펭귄 부리의 길이
bill_depth_mm float64 펭귄 부리의 깊이
flipper_length_mm float64 펭귄의 지느러미 길이
body_mass_g float64 펭귄의 체중
sex object 펭귄의 성별
입력 예시 1
island
출력 예시 1
bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
island
Biscoe 44.300000 15.854839 207.709677 4671.774194
Dream 43.762500 18.459375 192.437500 3599.218750
Torgersen 39.133333 17.883333 187.500000 3716.666667
입력 예시 2
species,island
출력 예시 2
bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
species island
Adelie Biscoe 38.800000 18.255556 188.333333 3627.777778
Dream 37.520000 18.320000 188.733333 3486.666667
Torgersen 39.133333 17.883333 187.500000 3716.666667
Chinstrap Dream 49.270588 18.582353 195.705882 3698.529412
Gentoo Biscoe 46.550000 14.872727 215.636364 5098.863636
내가 한 풀이
import pandas as pd
import numpy
# 1. penguins.csv 파일을 읽어옵니다.
df = pd.read_csv("penguins.csv")
# print(df)
# 2. 첫번째 줄에 그룹화할 기준의 컬럼명을 입력받습니다.
# - 그룹화할 컬럼은 최소 한 개에서 최대 두 개까지 입력받습니다.
# - 입력하는 컬럼은 , 로 구분됩니다.
column_name = input("그룹화할 기준의 컬럼명 한개~두개 입력 ,로 구분: ")
column_names = [col.strip() for col in column_name.split(",")]
num_columns = len(column_names)
print(column_names)
# 3. 첫 번째 줄에 입력받은 컬럼 명을 기준으로 순서대로 그룹화한 후, 평균을 구하여 출력합니다.
# 숫자형 자료에 대해서만 출력합니다.
# (mean 메서드 사용시 numeric_only 인자에 True를 전달하면 숫자형 자료에 대해서만 출력할 수 있습니다.)
if num_columns == 2:
df[column_names[1]] = pd.to_numeric(df[column_names[1]])
print(df.groupby(column_names[0])[column_names[1]].mean())
else:
try:
df[column_name] = pd.to_numeric(df[column_name])
print(df[column_name].mean())
except ValueError as e:
print(f"'{column_name}'에는 숫자(정수/실수)로 변환할 수 없는 데이터가 포함되어 있습니다. {e}")
except Exception:
print('알수 없는 에러 발생')
다른 사람의 풀이
import pandas as pd
# 1. penguins.csv 파일을 읽어옵니다.
df = pd.read_csv("penguins.csv")
# 2. 첫번째 줄에 그룹화할 기준의 컬럼명을 입력받습니다.
# - 그룹화할 컬럼은 최소 한 개에서 최대 두 개까지 입력받습니다.
# - 입력하는 컬럼은 , 로 구분됩니다.
group_columns = input("그룹화할 기준의 컬럼명 한개~두개 입력: ").split(",")
grouped = df.groupby(group_columns)
print(grouped.mean(numeric_only=True))
# 3. 첫 번째 줄에 입력받은 컬럼 명을 기준으로 순서대로 그룹화한 후, 평균을 구하여 출력합니다.
# 숫자형 자료에 대해서만 출력합니다.
# (mean 메서드 사용시 numeric_only 인자에 True를 전달하면 숫자형 자료에 대해서만 출력할 수 있습니다.)
아마 문제 의도랑 많이 달랐던거 같다. 나는 평균화를
여기는 그룹화를 했으니
이렇게 수정하면 요구사항에 맞는 풀이가 되겠다.
import pandas as pd
import numpy
# 1. penguins.csv 파일을 읽어옵니다.
df = pd.read_csv("penguins.csv")
# print(df)
# 2. 첫번째 줄에 그룹화할 기준의 컬럼명을 입력받습니다.
# - 그룹화할 컬럼은 최소 한 개에서 최대 두 개까지 입력받습니다.
# - 입력하는 컬럼은 , 로 구분됩니다.
column_name_input = input("그룹화할 기준의 컬럼명 한개~두개 입력 ,로 구분: ")
column_names = [col.strip() for col in column_name_input.split(",")]
# print(f"\n입력된 컬럼: {column_names}")
# 3. 입력받은 컬럼 명을 기준으로 순서대로 그룹화한 후, 평균을 구하여 출력합니다.
# 숫자형 자료에 대해서만 출력합니다.
try:
# 입력된 컬럼으로 그룹화하고, 전체 숫자형 컬럼에 대해 평균 계산
# .mean(numeric_only=True)를 사용하여 숫자형 컬럼에 대해서만 계산
grouped_mean = df.groupby(column_names).mean(numeric_only=True)
# print("\n## 📊 그룹별 숫자형 컬럼 평균 결과:")
print(grouped_mean)
except KeyError:
print(f"\n❌ 오류: 입력하신 컬럼명 중 데이터프레임에 존재하지 않는 이름이 있습니다: {column_names}")
except ValueError:
print(f"\n❌ 오류: 그룹화 기준 컬럼은 1개 또는 2개여야 합니다. 현재 입력: {len(column_names)}개")
인도에서 스마트폰, 데스크탑, 태블릿PC 점유율을 기록한 csv 파일을 이용하여 csv 파일을 기준에 따라 그룹화하고 특정 인덱스의 최댓값을 구하려고 합니다. 파일 내의 컬럼에 대한 설명은 다음과 같습니다.
컬럼 명 형식 내용
Date object 측정 날짜
Mobile float64 모바일 시장 점유율
Desktop float64 데스크탑 시장 점유율
Tablet float64 태블릿PC 시장 점유율
입력 예시
Month
출력 예시
Mobile Desktop Tablet Year
Month
1 57.332667 42.156667 0.510000 2016
2 56.698000 42.801333 0.501333 2016
3 57.479333 42.007333 0.512667 2016
4 58.248667 41.222000 0.530667 2016
5 58.652667 40.799333 0.546667 2016
6 58.950000 40.497333 0.552000 2016
7 58.965333 40.487333 0.547333 2016
8 59.707333 39.724000 0.567333 2016
9 60.142667 39.306667 0.550667 2016
10 60.892000 38.572667 0.534000 2016
11 61.545333 37.924667 0.530000 2016
12 62.525333 36.951333 0.524667 2016
내가 한 풀이
# 1. india_shares.csv 파일을 읽어옵니다.
import pandas as pd
df = pd.read_csv("india_shares.csv")
# 2. Date 컬럼을 활용해서 연, 월 데이터를 아래의 컬럼을 만들어서 저장하세요.
# - Year : Date 컬럼의 연에 해당하는 데이터
# - Month : Date 컬럼의 월에 해당하는 데이터
df["Year"] = pd.to_datetime(df["Date"]).dt.year
df["Month"] = pd.to_datetime(df["Date"]).dt.month
# df
# 3. 그룹화할 기준의 컬럼 명 하나를 입력받습니다.
# 4. 불러온 csv 파일을 이용하여 입력받은 컬럼 명을 기준으로 순서대로 그룹화한 후, 평균을 구하여 출력합니다.
# 5. 숫자형 자료에 대해서만 출력합니다.
# (mean 메서드 사용시 numeric_only 인자에 True를 전달하면 숫자형 자료에 대해서만 출력할 수 있습니다.)
try:
column_name = input("컬럼명을 입력해주세요.: ")
avg = df.groupby(column_name).mean(numeric_only=True)
print(avg)
except ValueError:
print('입력이 옳지 않습니다.')
except Exception:
print('알수 없는 오류 발생')
예외처리문에 numeric_only=True까지 넣어 숫자형 자료에 대해서만 평균 구하게 처리
다른 사람의 풀이
import pandas as pd
df = pd.read_csv('india_shares.csv') # 데이터 셋 읽어오기
df['Date'] = pd.to_datetime(df['Date']) # 1. Date 컬럼 날짜 타입으로 변경
df['Year'] = df['Date'].dt.year # year 컬럼 추출
df['Month'] = df['Date'].dt.month # month 컬럼 추출
column = input() # 그룹화할 컬럼의 이름을 입력받기
grouped = df.groupby(column) # 입력받은 컬럼으로 그룹화
df_mean = grouped.mean(numeric_only=True) # 숫자형 데이터에 대해 펴균을 각 그룹마다 전체 컬럼에 대해
print(df_mean)
좀더 단순하나 Date는 굳이 컬럼으로 만들 필욘 없었다.