如何在不同条件下过滤数据帧

2024-09-28 04:46:58 发布

您现在位置:Python中文网/ 问答频道 /正文

从输入创建输出数据帧,在每个id的target==1时第一次筛选行,或者在target为1的每个id中删除连续出现的字,但是在target=1之前保留target中的所有0,并在没有1的位置保留一组id,例如a0

输入

df = pd.DataFrame({'ID': ['a0','a0','a0','a1', 'a1', 'a1', 'a1', 'a1', 'a2', 'a2', 'a2', 'a2'],
 'date': [ '2019-11-01',
  '2019-12-01',
  '2020-01-01',
  '2019-11-01',
  '2019-12-01',
  '2020-01-01',
  '2020-02-01',
  '2020-03-01',
  '2019-11-01',
  '2019-12-01',
  '2020-03-01',
  '2020-04-01'],
 'target': [0,0,0,0, 0, 1, 1, 0, 0, 1, 0, 1]})

输出

ID   date         target
a0   2019-11-01   0
a0   2019-12-01   0
a0   2020-01-01   0
a1   2019-11-01   0
a1   2019-12-01   0
a1   2020-01-01   1
a2   2019-11-01   0
a2   2019-12-01   1

Tags: 数据ida2targetdataframedfdatea1
3条回答

问得好。我相信Ferris的答案可能是一种优雅且计算效率高的方法。另一种直观的方法是考虑在数据帧上使用“apply”函数为排序后的数据帧中的每个组生成索引,直到我们应该在输出中包括哪一行

df["ind"]=df.index

upto_id_index = df.groupby("ID").apply(lambda x: x[(x["target"]==1)]["ind"].min() if (x["target"].sum()>0) else x["ind"].max())

df[df.apply(lambda x: x["ind"]<= upto_id_index.loc[x["ID"]], axis=1)]

首先对数据帧进行排序

df.sort_values(['ID', 'date'], inplace=True)

# use cumsum to calculate how many times the target eq 1
df['tag'] = df['target'] == 1 
df['tag'] = df.groupby('ID')['tag'].cumsum()

# for every group use shift(1) to include the first 1
df['tag2'] = df.groupby('ID')['tag'].shift(1).fillna(0)
cond = df['tag2'] == 0
df[cond]

结果:

   ID        date  target  tag  tag2
0  a0  2019-11-01       0  0.0   0.0
1  a0  2019-12-01       0  0.0   0.0
2  a0  2020-01-01       0  0.0   0.0
3  a1  2019-11-01       0  0.0   0.0
4  a1  2019-12-01       0  0.0   0.0
5  a1  2020-01-01       1  1.0   0.0
8  a2  2019-11-01       0  0.0   0.0
9  a2  2019-12-01       1  1.0   0.0

df:

   ID        date  target  tag  tag2
0   a0  2019-11-01       0  0.0   0.0
1   a0  2019-12-01       0  0.0   0.0
2   a0  2020-01-01       0  0.0   0.0
3   a1  2019-11-01       0  0.0   0.0
4   a1  2019-12-01       0  0.0   0.0
5   a1  2020-01-01       1  1.0   0.0
6   a1  2020-02-01       1  2.0   1.0
7   a1  2020-03-01       0  2.0   2.0
8   a2  2019-11-01       0  0.0   0.0
9   a2  2019-12-01       1  1.0   0.0
10  a2  2020-03-01       0  1.0   1.0
11  a2  2020-04-01       1  2.0   1.0

使用np.argmax获取第一个元素的索引是可行的,但是如何将所有行保留为0,其中每个id没有target=1 使用不同数据集(Pandas advanced groupby and filter by date)的上一篇文章

相关问题 更多 >

    热门问题