一、动手实战环节
实战1:csv模式创建
1.weather_data 有表头
import pandas as pd
df =pd.read_csv('weather_data.csv')
print(df)
print(df.columns) # 查看表头
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210405230201710.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODA5NDEwMA==,size_16,color_FFFFFF,t_70)
2.weather_data2 无表头/添加表头
df =pd.read_csv('weather_data2.csv',header =None) # header =None 设置无表头,默认0,1,2,3
print(df)
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021040523033517.png)
df.columns=['day', 'temperature', 'windspeed', 'event'] # 添加表头列表
print(df)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210405230351450.png)
实战2:excel方式创建
df2 = pd.read_excel('weather_data.xlsx',"Sheet1")
print(df2)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210405231312636.png)
实战3:字典创建法
1.使用字典的方式创建
import pandas as pd
# 使用字典的方式创建
weather_data = {
'day':[' 1/2/2021','1/3/2021 ',' 1/4/2021','1/5/2021 ','1/6/2021 '],
'temperature':[32,31,26,28,29],
'windspeed':[6,3,5,4,2],
'event':['Rain','Snow','Sunny','Sunny','Sunny']
}
print(pd.DataFrame(weather_data))
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021040606393345.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODA5NDEwMA==,size_16,color_FFFFFF,t_70)
2.增加一个新列event
import pandas as pd
weather_data = {
'day':[' 1/2/2021','1/3/2021 ',' 1/4/2021','1/5/2021 ','1/6/2021 '],
'temperature':[32,31,26,28,29],
'windspeed':[6,3,5,4,2],
}
df = pd.DataFrame(weather_data)
event = ['Rain','Snow','Sunny','Sunny','Sunny']
df['event']=event # 增加一个新列event
print(df)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210406064435168.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODA5NDEwMA==,size_16,color_FFFFFF,t_70)
实战4:元组创建法
import pandas as pd
weather_data = [('1/2/2021',32,6,'Rain'),('1/4/2021',31,3,'Snow'),('1/5/2021',26,5,'Sunny')] # 使用元组的方式创建
df = pd.DataFrame(data = weather_data,columns = ['day', 'temperature', 'windspeed', 'event'] ) # 添加表头
print(df)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210406065331153.png)
实战5:多元素字典创建法
import pandas as pd
# 列表字典
weather_data =[{'day':'1/2/2021','temp':32,'windspeed':5,'event':'Snow'},
{'day':'1/3/2021','temp':31,'windspeed':6,'event':'Rain'},
{'day':'1/4/2021','temp':30,'windspeed':7,'event':'Snow'},
{'day':'1/5/2021','temp':29,'windspeed':8,'event':'Sunny'}]
print(pd.DataFrame(weather_data ))
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210406065952599.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODA5NDEwMA==,size_16,color_FFFFFF,t_70)