如何向orig_diff添加列“main_category”,该列将指示子类别属于哪个主要类别。例如,值为“Movie”的orig_df必须将“main_category”设置为“Entertainment”,将“Maths”设置为“Education”。
import pandas as pd
import numpy as np
orig_df = pd.DataFrame({"sub_cat" : ["Movie", "Science", "Maths", "Music", "Songs", "Dance", "English", "Maths", "Songs"], "Student": ["Stud1", "Stud2", "Stud3", "Stud4", "Stud5", "Stud6", "Stud7", "Sud8", "Stud9"]})
sub_df = pd.DataFrame({"Education": [0,1,1,0,0,0,1], "Entertainment": [1,0,0,1,1,1,0]}, index=["Movie", "Science", "Maths", "Music", "Songs", "Dance", "English"])
print(orig_df)
print(sub_df)
答案 0 :(得分:1)
一种方法是通过迭代行从sub_df
创建一个字典。
然后在orig_df['sub_cat']
上使用字典作为地图:
d = {idx: next(k for k in sub_df if row[k]==1)
for idx, row in sub_df.iterrows()}
orig_df['main_category'] = orig_df['sub_cat'].map(d)
print(orig_df)
Student sub_cat main_category
0 Stud1 Movie Entertainment
1 Stud2 Science Education
2 Stud3 Maths Education
3 Stud4 Music Entertainment
4 Stud5 Songs Entertainment
5 Stud6 Dance Entertainment
6 Stud7 English Education
7 Sud8 Maths Education
8 Stud9 Songs Entertainment
请注意,这假设每个sub_cat
仅映射到“教育”或“娱乐”中的一个。