我有一个包含 2 列的数据框 DF:
CLASS STUDENT
'Sci' 'Francy'
'Sci' Vacant
'math' 'Alex'
'math' 'Arthur'
'math' 'Katy'
'eng' 'Jack'
'eng' Vacant
'eng' 'Francy'
'Hist' 'Francy'
'Hist' 'Francy'
我需要所有类(class)都有 1 个空缺 学生。其中一些已经有了。
结果
CLASS STUDENT
'Sci' 'Francy'
'Sci' Vacant
'math' 'Alex'
'math' 'Arthur'
'math' 'Katy'
'math' Vacant
'eng' 'Jack'
'eng' Vacant
'eng' 'Francy'
'Hist' 'Francy'
'Hist' 'Francy'
'Hist' Vacant
我试过了
unique_class = DF['unique_class'].drop_duplicates()
vacant_column = pd.Series(['vacant'] * unique_class.shape[0])
temp_df = pd.concat([unique_class, vacant_column], axis=1, ignore_index=True)
DF = DF.append(temp_df, ignore_index=True)
DF.drop_duplicates(inplace=True)
它有效,但似乎太多了。有更好的方法吗?
请您参考如下方法:
还有另一种方法:
# Copy of your data
df = pd.DataFrame({
"class": ["Sci", "Sci", "math", "math", "math", "eng", "eng", "eng", "Hist", "Hist"],
"student": ["Francy", "vacant", "Alex", "Arthur", "Katy", "Jack", "vacant", "Francy", "Francy", "Francy"]
})
# An identical DF with all students equal to "vacant"
vacant_df = pd.DataFrame({"class": df["class"], "student": "vacant"})
# Remove existing 'vacant' from original DF and concatenate with de-duplicated vacant dataframe (to avoid duplicate 'vacant' entries)
final_df = pd.concat([df.loc[df.student != "vacant", vacant_df.drop_duplicates("class")])
原始DF:
class student
8 Hist Francy
9 Hist Francy
0 Sci Francy
1 Sci vacant
5 eng Jack
6 eng vacant
7 eng Francy
2 math Alex
3 math Arthur
4 math Katy
最终DF:
class student
8 Hist Francy
9 Hist Francy
8 Hist vacant
0 Sci Francy
0 Sci vacant
5 eng Jack
7 eng Francy
5 eng vacant
2 math Alex
3 math Arthur
4 math Katy
2 math vacant
