## 2.7 課堂活動1——了解你的班級
```
#任務1 最受歡迎的愛好或生活習慣
import pandas as pd
# 讀取Excel文件
df = pd.read_excel('3227.xlsx').dropna()
# 假設除了姓名和性別列之外,其他列都是評分數據
# 選擇評分數據列,并轉換為整數類型
scores = df.iloc[:, 2:].astype(int)
# 計算每列的總分
total_scores = scores.sum()
# 找到總分最高的列名,即最喜愛的項目
most_popular_item = total_scores.idxmax()
# 打印結果
print(f"全班最喜愛的項目是:{most_popular_item}")
# 任務2:找出生活習慣不太好的同學,并提醒他。
#尋找規則:愛吃火鍋或燒烤 且 喜愛點外賣 且 作息不好或愛熬夜
import pandas as pd
# 讀取Excel文件
df = pd.read_excel('3227.xlsx').dropna()
df1 = df.iloc[:, 2:].astype(int)
# 定義篩選條件
condition1 =(df1['火鍋'] > 3) | (df1['燒烤'] > 3)
condition2 = df1['點外賣'] > 3
condition3 =(df1['早睡早起']<2) |(df1['熬夜'] > 3)
# 組合所有條件
combined_condition = condition1 & condition2 & condition3
# 篩選出滿足條件的同學
filtered_df = df1[combined_condition]
# 打印篩選結果
print(filtered_df)
df.loc[14]
```
## 2.7 課堂活動2——尋找與你“相似”的同學
```
import pandas as pd
import numpy as np
# 讀取Excel文件,假設文件名為'students_data.xlsx'且位于當前工作目錄
file_path = '3227.xlsx'
#讀取時去掉沒填的同學的行
df = pd.read_excel(file_path).dropna()
# 初始化一個空字典來存儲整理后的數據
students = {}
# 遍歷數據框的每一行,假設學生姓名在第一列
for index, row in df.iterrows():
student_name = row['學生姓名'] # 獲取學生姓名
# 從第二列開始,到最后一列(不包含空列),提取數據并轉換為numpy數組
scores = np.array(row.tolist()[1:])
# 將學生姓名和對應的分數數組添加到字典中
students[student_name] = scores
# 打印整理后的數據結構
print(students)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 計算兩個向量(商品)之間的內積
def inner_product(vec1, vec2):
return np.dot(vec1, vec2)
#找出相速度最高的菜
def findSimilar(x):
# 獲取給定菜品的特征向量
target_vec = students[x]
# 初始化最大相似度和最相似菜品
max_similarity = 0.0
most_similar_student = None
# 遍歷所有菜品,計算與給定菜品的內積
for student, vec in students.items():
if student != x: # 排除自身
similarity = inner_product(target_vec, vec)
# 如果當前內積大于之前的最大相似度,則更新最大相似度和最相似菜品
if similarity > max_similarity:
max_similarity = similarity
most_similar_student = student
# 返回最相似菜品和相似度
return most_similar_student, max_similarity
```
## 3.1 API接口獲取天氣數據
```python
import requests
import json
#知心天氣官網:
#東軟秘鑰
#eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY4ZTQ3ZjFiLTRjMmYtNDBiOS1iZmY4LWQ3YTg3MGFiYzcwMiJ9._TrSam5rj-3EGY2GwEg4qzpEgqWC6fFV5BoS1YILYVOGwllPjw8mHG3SO2nhuaiIhT7oBs-hKrkBam03dW159Q
def fetch_weather_data():
# 構建請求的URL
#url = f"http://124.93.196.45:10001/dev-api/bs-weather-report/weather/getCurrentDayData/上海市"
#url = f"https://route.showapi.com/9-2?showapi_appid=1581147&showapi_sign=3a013bb035394181947e42fff8287556&area=南通"
url = "https://api.seniverse.com/v3/weather/daily.json?key=SND4L7mkeZRVCghJH&location=nantong&language=zh-Hans&unit=c&start=0&days=5"
# 設置請求頭,包含認證參數 -東軟
# headers = {
# 'Authorization': f'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY4ZTQ3ZjFiLTRjMmYtNDBiOS1iZmY4LWQ3YTg3MGFiYzcwMiJ9._TrSam5rj-3EGY2GwEg4qzpEgqWC6fFV5BoS1YILYVOGwllPjw8mHG3SO2nhuaiIhT7oBs-hKrkBam03dW159Q'
# }
# 發送GET請求,包含請求頭
#response = requests.get(url, headers=headers)
response = requests.get(url)
# 檢查請求是否成功
if response.status_code == 200:
# 解析返回的JSON數據
data = response.json()
city = data["results"][0]["location"]["name"]
list = data["results"][0]["daily"]
# print(list)
# for a in list:
# print(a["date"])
weather_data = {
'city': city,
'weatherList': list,
}
return weather_data
weather_data = fetch_weather_data()
weather_data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from IPython.display import display,Image
print(weather_data["city"])
print("~~~~~~~~~~~~~~~~~~~~~~~華麗分隔線~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
for daily_weather in weather_data["weatherList"]:
print("日期:"+daily_weather["date"])
print("天氣:"+daily_weather["text_day"])
print("溫度:"+daily_weather["low"]+"--"+daily_weather["high"]+"℃")
display(Image(f"{daily_weather['text_day']}.png"))
# print(file_path)
# print(daily_weather)
print("~~~~~~~~~~~~~~~~~~~~~~~華麗分隔線~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
```
## 3.2 充電樁查詢
```
#任務1 將所有的充電樁數據轉換為Excel可編輯的文件
import requests
import json
import pandas as pd
def fetch_weather_data():
# 構建請求的URL
url = f"http://124.93.196.45:10001/dev-api/bs-smart-charger/pile/alllist"
# 設置請求頭,包含認證參數 -東軟
headers = {
'Authorization': f'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY4ZTQ3ZjFiLTRjMmYtNDBiOS1iZmY4LWQ3YTg3MGFiYzcwMiJ9._TrSam5rj-3EGY2GwEg4qzpEgqWC6fFV5BoS1YILYVOGwllPjw8mHG3SO2nhuaiIhT7oBs-hKrkBam03dW159Q'
}
# 發送GET請求,包含請求頭
response = requests.get(url, headers=headers)
#response = requests.get(url)
# 檢查請求是否成功
if response.status_code == 200:
# 解析返回的JSON數據
data = response.json()
pileList = data['data']
print(type(pileList))
df = pd.DataFrame(pileList)
print(df)
return df
df = fetch_weather_data()
df.to_excel('output.xlsx')
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#任務2 查詢:目前是空閑狀態且充電速率快的充電樁。
def fetch_weather_data():
# 構建請求的URL
url = f"http://124.93.196.45:10001/dev-api/bs-smart-charger/pile/alllist?chargingPileState=2&chargingPileRate=2"
# 設置請求頭,包含認證參數 -東軟
headers = {
'Authorization': f'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY4ZTQ3ZjFiLTRjMmYtNDBiOS1iZmY4LWQ3YTg3MGFiYzcwMiJ9._TrSam5rj-3EGY2GwEg4qzpEgqWC6fFV5BoS1YILYVOGwllPjw8mHG3SO2nhuaiIhT7oBs-hKrkBam03dW159Q'
}
# 發送GET請求,包含請求頭
response = requests.get(url, headers=headers)
#response = requests.get(url)
# 檢查請求是否成功
if response.status_code == 200:
# 解析返回的JSON數據
data = response.json()
pileList = data['data']
df = pd.DataFrame(pileList)
print(df)
return df
fetch_weather_data()
```