Python 根据条件删除组中的最后一行
我想根据条件删除组中的最后一行。我已经做了以下工作:Python 根据条件删除组中的最后一行,python,pandas,dataframe,boolean,rows,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 201
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
当我这样做时,我只会得到:
KeyError:错误
我期望的结果是:
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-out
,则只需通过dict
将非数值in-out
映射到数值,因为滚动
不使用字符串:
#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
一种简单的方法是在打开.csv文件时添加skipfooter=1
:
df = pd.read_csv(file, skipfooter=1, engine='python')
问题是我需要先遍历每个人(因此是组),然后删除最后一行,如果它不是以“out”结尾的话。因为现在我已经知道了如果行与上面的行不相似,如何删除该行:df=df.loc[df['profuct'].shift()!=df['product']]我想我的问题可能只是稍微改变了一点。。。如果列“product”.eq('in')@LouiseMa-hmmm不理解,我如何访问每个列“id”中的最后一行并删除该行。主要写您需要删除每个组的最后一个id,您的预期输出生成每个组的in-out
值,现在在注释中需要其他内容。所以现在我很困惑,到底需要什么…嗯,对不起。。。好的,我试着输入第二个解决方案,我得到了一个错误:“TypeError:无法解包不可iterable int object”@LouiseMa-好的,我能问点什么吗?每个组是否需要一对in-out
?@jezrael我知道你的答案要好得多,这只用于删除最后一行。max这只删除csv文件上的最后一行,不符合上述条件。
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
df = pd.read_csv(file, skipfooter=1, engine='python')