【发布时间】:2020-04-06 02:44:18
【问题描述】:
我目前有一个跟踪已完成 5 次测试的数据集,但是,它只显示已完成测试的人,而不是尚未参加测试的人 - 示例如下:
Name Test Completed
John Math-Test1 Yes
John Math-Test2 Yes
John Math-Test3 Yes
John Math-Test4 Yes
John Math-Test5 Yes
Lauren Math-Test1 Yes
Lauren Math-Test2 Yes
Lauren Math-Test3 Yes
Tom Math-Test1 Yes
Tom Math-Test2 Yes
Tom Math-Test3 Yes
Tom Math-Test4 Yes
Tom Math-Test5 Yes
如您所见,Lauren 尚未参加“Math-Test4”和“Math-Test5”测试,因此她的名字没有出现。我想添加一个选项,让“已完成”列在有人未完成测试时显示“否”。
所需的输出如下:
Name Test Completed
John Math-Test1 Yes
John Math-Test2 Yes
John Math-Test3 Yes
John Math-Test4 Yes
John Math-Test5 Yes
Lauren Math-Test1 Yes
Lauren Math-Test2 Yes
Lauren Math-Test3 Yes
*Lauren Math-Test4 No* - Add these rows automatically
*Lauren Math-Test5 No*
Tom Math-Test1 Yes
Tom Math-Test2 Yes
Tom Math-Test3 Yes
Tom Math-Test4 Yes
Tom Math-Test5 Yes
如何使用 Python/Pandas/Numpy 实现这一点?
感谢所有可以提供帮助的人!
编辑 - 更新:在尝试@Scott Boston 的代码后,我得到了这个:
idx = pd.MultiIndex.from_product([df['Name'].unique(),
df['Test'].unique()],
names=['Name','Test'])
newidx = idx[~idx.isin(df.set_index(['Name','Test']).index)]
pd.concat([df,
newidx.to_series().reset_index().assign(Completed="No*")[['Name','Test','Completed']]], ignore_index=True)
输出:
Name1 Test Completed
John Math-Test1 Yes
John Math-Test2 Yes
John Math-Test3 Yes
John Math-Test4 Yes
John Math-Test5 Yes
Lauren Math-Test1 Yes
Lauren Math-Test2 Yes
Lauren Math-Test3 Yes
Tom Math-Test1 Yes
Tom Math-Test2 Yes
Tom Math-Test3 Yes
Tom Math-Test4 Yes
Tom Math-Test5 Yes
John Math-Test3 No*
John Math-Test4 No*
John Math-Test5 No*
John Math-Test2 No*
Lauren Math-Test3 No*
Lauren Math-Test4 No*
Lauren Math-Test5 No*
Lauren Math-Test2 No*
Lauren Math-Test5 No*
Lauren Math-Test1 No*
Lauren Math-Test2 No*
Lauren Math-Test4 No*
Lauren Math-Test5 No*
现在只需要找到方法来删除不需要的行以获得所需的输出。
【问题讨论】:
标签: python pandas numpy conditional-statements rows