问题描述
我正在尝试根据第一天的值查找重复的 ID。
例如,我有 4 天的记录:
import pandas as pd
df = pd.DataFrame({'id':['1','2','5','4','3','4'],'class':['1','1','0','1'],'day':['1','4']})
df
根据以上数据,我想找出符合以下条件的记录: (1) day=1 中所有class = 0的记录; (2)第2、3、4天,如果id满足条件(1),则保留记录--在第1天有class=0
所以结果应该是:
df = pd.DataFrame({'id':['5','class':['0','4']})
df
此方法有效:
# 1. find unique id in day 1 that meet condition (1)
df1 = df[(df['day']=='1') & (df['class']=='0')]
df1_id = df1.id.unique()
# 2. create a new dataframe for day 2,3,4
df234=df[df['day']!='1']
# 3. create a new dataframe for day2,4 that contains the id in the unique list
df234_new = df234[df234['id'].isin(df1_id)]
#4. append df234_new at the end of df1
df_new = df1.append(df234_new)
df_new
但是我的完整数据集包含更多的列和行,使用上述方法听起来太乏味了。有谁知道如何更有效地做到这一点?非常感谢!!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)