题目分析
一、题目要求
- 使用Pandas读取数据;
- 现有的“date”列没有包含星期信息,需要根据其额外生成一列“week”,表示星
期,例如“星期一”; - 将温度处理成整型,例如将5℃处理成5,注意,其中含有非法字符,需要自行进
行合理的处理; - 风力列(wind)包含风向和风力等级,需要将其处理为两列,分别为
wind_direction(风向)和wind_level(风力等级); - 处理之后的列名包括’id’, ‘city’, ‘date’, ‘week’, ‘hightest_tem’, ‘lowest_tem’,
‘weather’, ‘wind_direction’, ‘wind_level’;将其重命名为’ID’, ‘城市’, ‘日期’, ‘星期’, ‘最
高温度’, ‘最低温度’, ‘天气’, ‘风向’, ‘风力等级’;
二、对应的数据
实现过程
1.读取数据
import pandas as pd
import datetime as dt
df = pd.read_csv('./data/day.csv')
print(df)
2.将日期处理成对应的星期几
def gen_week_day(date_str):
'''
根据日期生成星期
:param date:
:return:
'''
date = dt.datetime.strptime(date_str, '%Y-%m-%d')
week_day = date.weekday()
# print(week_day)
week_dic = {0: "星期一", 1: "星期二", 2: "星期三", 3: "星期四", 4: "星期五", 5: "星期六", 6: "星期日"}
return week_dic[week_day]
3.使用apply将那一列每一个值都使用gen_week_day
df['week'] = df['date'].apply(gen_week_day) #
print(df)
4.将温度异常的数据提取成对应的温度,主要有如下图的问题,比如–和°℃
# 负号和对应的数字提取出来
def deal_tem(tem_str):
'''
提取负号和数字
:param tem_str:
:return:
'''
i = 0
res = ""
while i < len(tem_str):
if i + 1 < len(tem_str) and tem_str[i + 1] == '-' and tem_str[i] == '-':
res += '-'
i += 2
elif tem_str[i] == '-':
res += '-'
i += 1
elif tem_str[i].isdigit():
res += tem_str[i]
i += 1
else:
i += 1
return int(res)
5.在最高温以及最低温那里使用apply,将最高温以及最低温都使用deal_tem计算每一列的每一个值
df['hightest_tem'] = df['hightest_tem'].apply(deal_tem)
df['lowest_tem'] = df['lowest_tem'].apply(deal_tem)
print(df)
6.得到对应的风向等级
def deal_wind(wind_str):
'''
得到风向和等级
:param wind_str:
:return:
'''
try:
feng_index = wind_str.find('风')
win_direct = wind_str[:feng_index + 1]
for idx in range(feng_index, len(wind_str)):
if wind_str[idx].isdigit:
level_index = idx
break
wind_level = wind_str[level_index:]
return win_direct, wind_level
except Exception:
return '', ''
7.应用到这两列
df['wind_direction'] = df['wind'].apply(lambda x: deal_wind(x)[0])
df['wind_level'] = df['wind'].apply(lambda x: deal_wind(x)[1])
8.更改对应的列名
df = df[['id', 'city', 'date', 'week', 'hightest_tem', 'lowest_tem', 'weather', 'wind_direction', 'wind_level']]
df.columns = ['ID', '城市', '日期', '星期', '最高温度', '最低温度', '天气', '风向', '风力等级']
9.保存对应的csv文件
df.to_csv('./data/result.csv', index=False)