我有一個數據框,其中包含一個工資列,指定一個小時工資和一個聯合列,指定員工是否在工會。還有其他變數,但現在它們並不重要。我試圖找到工會中員工的平均工資。我編寫了代碼,它提供了一個關於員工是否在工會中的真/假清單。但是,我不知道如何應用這份名單來獲得平均工資。預先感謝您的幫助。Python熊貓數據框控制流程
#Read cps.csv file
import pandas as pd
cps_df = pd.read_csv('cps.csv')
cps_df
#Function to determine whether or not an employee is in a union
def hourly_wage(x):
""" return true if union else false """
if x['union'] == 'Union':
return True
else:
return False
#Function to create a list of union vs non-union
def union_list(y):
""" return a list determining union vs non-union """
return [hourly_wage(x) for index, x in y.iterrows()]
#Print list
%time
print(union_list(cps_df))
也許我錯過了這裏的一些東西,但爲什麼不'cps_df [cps_df [''union'] =='Union'] ['wage']。mean()'? – iayork
我需要創建一個熊貓數據框,並通過使用控制流遍歷數據框的每一行來計算工會工人的平均小時工資。所以我猜我需要像這樣設置它。我錯了嗎? –