我有一個(gè)數(shù)據(jù)框 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和數(shù)據(jù)框類(lèi)別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我想做的是檢查類(lèi)別中“類(lèi)別”的值是否包含在 dfScores 列中。如果是,則將 dfScores 列中的值設(shè)置為“ScoreTruth”相鄰值。我嘗試使用 isin 來(lái)獲取 dfScores 列中的索引,但這實(shí)際上并沒(méi)有告訴我哪個(gè)類(lèi)別是哪個(gè)索引。IEindex = np.where(dfScore.columns.isin(categories["Category"]))print(index[0])>>>[1 2 3]如果我嘗試以相反的方式從 is 獲取索引,我會(huì)得到index2 = np.where(categories["Category"].isin(dfScore.columns))print(index2[0])>>>[0 1 2]所以現(xiàn)在我想我可以做這樣的事情dfScore.iloc[:,index[0]] = categories.iloc[index2[0]].loc["ScoreTruth"]來(lái)設(shè)置值,但我發(fā)現(xiàn)KeyError: 'ScoreTruth'顯然只有當(dāng)我使用索引 [0] 設(shè)置 dfScores 中的每一行時(shí)這才有效,這并不理想。我想輸出一個(gè)看起來(lái)像這樣的數(shù)據(jù)框 Name Sales total Problem total Finance total0 ringo 4 5 14
1 回答

犯罪嫌疑人X
TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
咱們?cè)囋嚢蒁ataFrame.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
添加回答
舉報(bào)
0/150
提交
取消