簡體   English   中英

使用itertools並將函數應用於每一行時,“ int”對象不可迭代”

[英]'int' object is not iterable" when use itertools and apply function to each row

我有以下數據集:

index    REWARD  
(1,1,1)   0
(1,2,3)   0
(1,1,3)   0

如果索引有一對數字,我想設置REWARD = 2。 所以輸出應該像

index    REWARD  
(1,1,1)   0
(1,2,3)   0
(1,1,3)   2

當我使用這段代碼

  def set_reward(final):
        for i in final['index']:
            tempCount=[]
            for item,count in collections.Counter((i)).items():
                tempCount.append(count)
            if tempCount==[2, 1] or tempCount==[1, 2]:
                final['REWARD']=2
            return final['REWARD']
    final['REWARD']=final.apply(set_reward,axis=1)

它說“ int”對象是不可迭代的”

有什么辦法解決嗎?

您無需顯式使用循環和條件邏輯即可獲得所需的結果。 嘗試這樣的事情:

# Example data
df = pd.DataFrame({'index':  [(1, 1, 1), (1, 2, 3), (1, 1, 3)], 
                   'REWARD': [0, 0, 2]})


# Select any row whose index contains at least one pair of values
mask = df['index'].apply(lambda x: 2 in Counter(x).values())

df.loc[mask, 'REWARD'] = 2

df
       index  REWARD
0  (1, 1, 1)       0
1  (1, 2, 3)       0
2  (1, 1, 3)       2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM