import pandas as pd
df = pd.read_csv(path_to_file.csv) # assuming the file has all the relevant fields
def calculate_price(row):
return row['price_per_room'] * row['number_of_rooms'] * row['number_of_nights']
df['price'] = df.apply(calculate_price)
average_price = df['price'].mean()
print(f"The average price is {average_price }")
## use group by to aggregate across categories
df = pd.DataFrame({
'neighbourhood' : ['nice', 'not so nice', 'nice', 'awesome', 'not so nice'],
'room_type' : ['a', 'a', 'b', 'b', 'a']
'beds': [7,2,1,6,6],
'bedrooms': [3,1,1,3,2],
'bathrooms': [2,1,1,1,1],
'price': [220,100,125,320,125]
})
print('Mean of all prices:\n', df['price'].mean())
print('\nMean grouped by neighbourhood:\n', df.groupby(['neighborhood']).mean().price)
print('\nMean grouped by more cols:\n', df.groupby(['neighbourhood', 'beds', 'bedrooms']).mean().price)
输出:
Mean of all prices:
178.0
Mean grouped by neighbourhood:
neighbourhood
awesome 320.0
nice 172.5
not so nice 112.5
Mean grouped by more cols:
neighbourhood beds bedrooms
awesome 6 3 320
nice 1 1 125
7 3 220
not so nice 2 1 100
6 2 125
您还可以在应用groupy之前过滤数据帧,例如:
# select requested data data in loc[...] and then apply groupby
df_filtered = df.loc[(df['neighbourhood']=='nice') & (df['beds']==1)]
df_filtered.groupby('neighbourhood')['price'].mean()
# or the same on one line:
df.loc[(df['neighbourhood']=='nice') & (df['beds']==1)].groupby('neighbourhood')['price'].mean()
您的函数(来自上一条评论)可能如下所示:
def calculate_price(air_df):
a = str(input("Enter the Neighbourhood : "))
b = str(input("Enter the Room Type : "))
c = float(input("Enter number of Beds : "))
d = float(input("Enter number of Bedrooms : "))
e = float(input("Enter number of Bathrooms : "))
return air_df.loc[
(air_df['neighbourhood']==a) &
(air_df['room_type']==b) &
(air_df['beds']==c) &
(air_df['bedrooms']==d) &
(air_df['bathrooms']==e)
].groupby('neighbourhood')['price'].mean()
如果你能提供更多的细节并提出具体的问题,这会有所帮助。你知道吗
大熊猫平均价格的计算方法如下:
希望这有帮助!你知道吗
我不确定你到底需要什么(你应该更详细地说明你的问题,添加示例数据,首选输出,你的代码……),但groupby可能有用。。。像这样:
输出:
您还可以在应用groupy之前过滤数据帧,例如:
您的函数(来自上一条评论)可能如下所示:
相关问题 更多 >
编程相关推荐