实验四
1. 创建一个DataFrame(df),用data做数据,labels做行索引。数据如下图
import pandas as pd
data={
'animal':['cat','cat','snake','dog','dog','cat','snake','cat','dog','dog'],
'age':[2.5,3.0,0.5,None,5.0,2.0,4.5,None,7.0,3.0],
'visits':[1,3,2,3,2,3,1,1,2,1],
'priority':['yes','yes','no','yes','no','no','no','yes','no','no'],
}
df1=pd.DataFrame(data,index=['a','b','c','d','e','f','g','h','i','j'])
print(df1)
2. 选择df中列标签为animal和age的数据,并输出。
w1=df1[['animal','age']]
print(w1)
3. 选择行为[3, 4, 8],且列为['animal', 'age']中的数据
print(df1.iloc[[3,4,8],[1,3]])
4. 选择animal为cat,且age小于3的行
df1[(df1['animal']=='cat')&(df1['age']<3)]
5. 将f行的age改为1.5
df1.replace(df1['age']==2.0,1.5,inplace=False)
6. 计算每种animal的平均age,分组输出。
df1[(df1['animal']=='cat')][['age']].mean
df1[(df1['animal']=='dog')][['age']].mean
df1[(df1['animal']=='snake')][['age']].mean