[英]How can I apply a function to each row in a pandas dataframe?
[英]How can I apply a function to a dataframe which needs a row index in Pandas?
我必須使用 ipums 的調查數據來獲得連續兩個時期失業的平均人數。 我寫了一個使用索引和數據框作為輸入的函數,
def u1(x,df):
if df.loc[x]['LABFORCE']==2 and df.loc[x]['CPSIDP']==df.loc[x+1]['CPSIDP']:
if df.loc[x]['EMPSTAT']==21 or df.loc[x]['EMPSTAT']==22:
return True
else:
return False
其中x
是索引, df
是數據幀。 CPSIDP
識別調查受訪者, LABFORCE
檢查受訪者是否在勞動力中,而EMPSTAT
是我需要用來檢查受訪者就業狀況的工具。
然后我計划使用apply
as
result= df.apply(u1, axis=1)
目前尚不清楚我應該在我的函數中傳遞什么參數(如果這種方法在哲學上是錯誤的,請告訴我)。 為索引傳遞數字或變量會給我一個“bool”對象不可調用錯誤。
產生錯誤的最小數據幀子集(最左邊的列是觀察的數量,它是我需要通過u1
的x
):
YEAR MONTH CPSIDP EMPSTAT LABFORCE
15285896 2018 7 20180707096701 10 2
15285926 2018 7 20180707098301 10 2
15285927 2018 7 20180707098302 10 2
15285928 2018 7 20180707098303 0 0
15285929 2018 7 20180707098304 0 0
15285930 2018 7 20180707098305 10 2
15286095 2018 7 20180707108203 21 2
IIUC 使用函數中的邏輯創建boolean
Series
會更有效。
這里&
是AND
運算符。
result = (df['LABFORCE'].eq(2) &
df['CPSIDP'].eq(df['CPSIDP'].shift()) &
df['EMPSTAT'].isin([21,22]))
result
15285896 False
15285926 False
15285927 False
15285928 False
15285929 False
15285930 False
15286095 False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.