python - 根据条件删除组中的最后一行

标签 python pandas dataframe boolean rows

我想根据条件删除组中的最后一行。我已完成以下操作:

df=pd.read_csv('file')
grp = df.groupby('id')
for idx, i in grp:
   df= df[df['column2'].index[-1] == 'In']

     id     product   date
 0   220    in      2014-09-01 
 1   220    out     2014-09-03 
 2   220    in      2014-10-16
 3   826    in     2014-11-11
 4   826    out     2014-12-09
 5   826    out      2014-05-19
 6   901    in      2014-09-01
 7   901    out     2014-10-05
 8   901    out     2014-11-01

当我这样做时,我只是得到: 关键错误:错误

我想要的输出是:

     id     product   date
 0   220    in      2014-09-01 
 1   220    out     2014-09-03
 3   826    in     2014-11-11
 4   826    out     2014-12-09 
 6   901    in      2014-09-01
 7   901    out     2014-10-05

最佳答案

如果只想删除每个组链中的最后一个in Series.duplicated~inSeries.ne 不相等:

df = df[~df['id'].duplicated() | df['product'].ne('in')]
print (df)
    id product        date
0  220      in  2014-09-01
1  220     out  2014-09-03
3  826      in  2014-11-11
4  826     out  2014-12-09
5  826     out  2014-05-19
6  901      in  2014-09-01
7  901     out  2014-10-05
8  901     out  2014-11-01

编辑:

如果想要每个组中所有可能的对in-out,请使用 this solution ,只需将非数字值 in-out 通过 dict 映射到数字,因为 rolling 不适用于字符串:

#more general solution
print (df)
     id product        date
0   220     out  2014-09-03
1   220     out  2014-09-03
2   220      in  2014-09-01
3   220     out  2014-09-03
4   220      in  2014-10-16
5   826      in  2014-11-11
6   826      in  2014-11-11
7   826     out  2014-12-09
8   826     out  2014-05-19
9   901      in  2014-09-01
10  901     out  2014-10-05
11  901      in  2014-09-01
12  901     out  2014-11-01

pat = np.asarray(['in','out'])
N = len(pat)

d = {'in':0, 'out':1}
ma  = (df['product'].map(d)
                   .groupby(df['id'])
                   .rolling(window=N , min_periods=N)
                   .apply(lambda x: (x==list(d.values())).all(), raw=False)
                   .mask(lambda x: x == 0) 
                   .bfill(limit=N-1)
                   .fillna(0)
                   .astype(bool)
                   .reset_index(level=0, drop=True)
             )
df = df[ma]
print (df)
     id product        date
2   220      in  2014-09-01
3   220     out  2014-09-03
6   826      in  2014-11-11
7   826     out  2014-12-09
9   901      in  2014-09-01
10  901     out  2014-10-05
11  901      in  2014-09-01
12  901     out  2014-11-01

关于python - 根据条件删除组中的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58581947/

相关文章:

python - DataFrame 中特定项目的值计数

python - 有没有办法直接将 python 输出发送到剪贴板?

python - 将列表的元素链接为树

python - 如果键满足条件,则减少 python 字典值

python - 如何有效地扩展/展平 Pandas 数据框

python - Python 数据框中的滚动回归估计

python - 如何在不改变尺寸的情况下减小 PNG 图像的文件大小?

python - 如果其他单元格包含 'something',如何在 2 个单元格中设置值

python - 在pandas df python中滚动计算坡度

python - 将索引和字符串连接到新列