temp/실습
실전 데이터 분석 실습: 유성우
시송
2025. 1. 8. 21:28
날짜 데이터
pd.to_datetime(20001099, format = %Y%m%d)
meteor_showers['startdate'] = pd.to_datetime(2020*10000
+ meteor_showers['startmonth']*100
+ meteor_showers['startday'], format='%Y%m%d')
.iterrows()
for ~ in df.iterrows()
- index-series(value) tuple쌍으로 접근해 df를 순회시켜주는 이터레이터 반환
- index, row에서 index는 위치 정보를, row는 해당 data의 인덱스 외 모든 정보를 columns-values 형태로 담고 있다.
for index, row in df.iterrows():
print(f"Index: {index}")
print(f"species: {row['species']}, sepal_length: {row['sepal_length']}, sepal_width: {row['sepal_width']}\n")
데이터프레임객체.at[인덱스번호, 컬럼이름] = 변경할 값
- at indexing: 행열이 지정된 특정 셀은 at으로 조회, 변경 가능
- 단일 스칼라값에 접근하는 가장 빠른 방법 (슬라이싱 불가)
# 첫 줄 값 변경
moon_phases.iloc[0,1] = 0
for index, row in moon_phases.iterrows():
if pd.isnull(row['percentage']):
# data(row)의 percentage가 null이면
moon_phases.at[index, 'percentage'] = moon_phases.at[index-1, 'percentage']
data만 반환
- .iloc[n] and .tolist()
- or not, series 형태로 돌아옴
# 도시명을 입력하면 위도와 별자리 리스트를 반환하는 함수 만들기
def predict_best_meteor_shower_viewing(city):
#city를 입력했을 때, cities의 'city'와(그 city를 찾고)
#그 city의 latitude의 컬럼 1행을 latitude 변수라 한다.
latitude = cities.loc[cities['city']==city, 'latitude'].iloc[0]
constellations_list= constellations.loc[(constellations['latitudestart']>=latitude) &
(constellations['latitudeend']<=latitude)
, 'constellation'].tolist()
return latitude, constellations_list
All code for 유성우
def predict_best_meteor_shower_viewing(city):
# 안내 메시지 초기화
meteor_shower_string = ''
# 입력한 도시 정보가 존재하지 않으면 오류 메시지
if city not in cities.values:
meteor_shower_string = "아쉽지만 " + city + "에서는 현재 유성우 예측이 어렵습니다."
return meteor_shower_string
# 도시의 위도 정보를 불러오기
latitude = cities.loc[cities['city'] == city, 'latitude'].iloc[0]
# 해당 도시의 위도에서 관측 가능한 별자리 조회
constellations_list = constellations.loc[(constellations['latitudestart'] >= latitude)&(constellations['latitudeend'] <= latitude), 'constellation'].tolist()
# 볼 수 있는 별자리가 존재하지 않으면 오류 메시지
if not constellations_list:
meteor_shower_string = "아쉽지만 " + city + "에서는 볼 수 있는 별자리가 없습니다."
return meteor_shower_string
# 별자리 관측 가능 안내 메시지
meteor_shower_string = city + "에서는 별자리 관측이 가능합니다: \n\n"
# 도시별 관찰 가능한 별자리 iterate
for constellation in constellations_list:
# 별자리와 가장 가까운 유성우 조회
meteor_shower = meteor_showers.loc[meteor_showers['radiant'] == constellation, 'name'].iloc[0]
# 유성우 관측이 가능한 시작일과 종료일
meteor_showers_startdate = meteor_showers.loc[meteor_showers['radiant'] == constellation,'startdate'].iloc[0]
meteor_showers_enddate = meteor_showers.loc[meteor_showers['radiant'] == constellation,'enddate'].iloc[0]
# 유성우가 보일 때의 달의 위상 조회
moon_phase_list = moon_phases.loc[(moon_phases['date'] >= meteor_showers_startdate) & (moon_phases['date'] <= meteor_showers_enddate)]
# 달이 눈에 보이는 첫 날 조회
best_moon_date = moon_phase_list.loc[moon_phase_list['percentage'].idxmin()]['date']
# 사용자에게 정보전달
meteor_shower_string += meteor_shower + '를 잘 보려면 ' + constellation + '자리 위치를 향하여 ' + best_moon_date.strftime('%Y-%m-%d') + '에 보면 됩니다.\n'
return meteor_shower_string
참고문헌