我有這個excel公式:=IF(L2="","",IF(COUNTIF($L$1:L2,L2)=1,"1YR",IF(COUNTIF($L$1:L2,L2)=2,"3YR","5YR")))正在用熊貓翻譯成軟件。這countif是一個棘手的問題,因為如果當前單元格中的值出現(xiàn)在當前單元格中,則只需要檢查和計數(shù)當前單元格上方的前一個單元格。目前的解決方案:df['year'] = np.where(df['company_id'] is None, None, np.where(pd.cut(df['company_id'], df.loc[df['company_id']].index[0]).count() == 1, '1YR', np.where(pd.cut(df.company_id, df.loc[df['company_id']].index[0]).count() == 2, '3YR', '5YR')))所需的輸出:company_id year48299 1YR48752 1YR48865 1YR48299 3YR49503 1YR48299 5YR49697 1YR50267 1YR50714 1YR50714 3YR51050 1YR使用pandas.cut函數(shù),但我認為這不是解決此問題的正確方法。任何朝著正確方向的幫助將不勝感激。
1 回答

慕斯王
TA貢獻1864條經(jīng)驗 獲得超2個贊
利用cumcount與反map利用詞典:
d = {0:'1YR', 1:'3YR', 2: '5YR'}
df['new'] = df.groupby(['company_id']).cumcount().map(d)
print (df)
company_id year new
0 48299 1YR 1YR
1 48752 1YR 1YR
2 48865 1YR 1YR
3 48299 3YR 3YR
4 49503 1YR 1YR
5 48299 5YR 5YR
6 49697 1YR 1YR
7 50267 1YR 1YR
8 50714 1YR 1YR
9 50714 3YR 3YR
10 51050 1YR 1YR
添加回答
舉報
0/150
提交
取消