我有一個數據框 dfScoredfScore = pd.DataFrame([["ringo", 0,0,0]], columns=["Name","Sales total","Problem total","Finance total"]) Name Sales total Problem total Finance total0 ringo 0 0 0和數據框類別data = [["Finance total", 14], ["Sales total", 4], ["Problem total", 5]] categories = pd.DataFrame(data, columns = ['Category', 'ScoreTruth']) Category ScoreTruth0 Finance total 141 Sales total 42 Problem total 5我想做的是檢查類別中“類別”的值是否包含在 dfScores 列中。如果是,則將 dfScores 列中的值設置為“ScoreTruth”相鄰值。我嘗試使用 isin 來獲取 dfScores 列中的索引,但這實際上并沒有告訴我哪個類別是哪個索引。IEindex = np.where(dfScore.columns.isin(categories["Category"]))print(index[0])>>>[1 2 3]如果我嘗試以相反的方式從 is 獲取索引,我會得到index2 = np.where(categories["Category"].isin(dfScore.columns))print(index2[0])>>>[0 1 2]所以現在我想我可以做這樣的事情dfScore.iloc[:,index[0]] = categories.iloc[index2[0]].loc["ScoreTruth"]來設置值,但我發現KeyError: 'ScoreTruth'顯然只有當我使用索引 [0] 設置 dfScores 中的每一行時這才有效,這并不理想。我想輸出一個看起來像這樣的數據框 Name Sales total Problem total Finance total0 ringo 4 5 14
1 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
咱們試試吧DataFrame.assign:
s = categories.set_index('Category')['ScoreTruth']
dfScore.assign(**s[s.index.intersection(dfScore.columns)])
Name Sales total Problem total Finance total
0 ringo 4 5 14
添加回答
舉報
0/150
提交
取消