我有一个数据框 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
提交
取消