Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据值计数列删除已排序行_Python_Pandas - Fatal编程技术网

Python 根据值计数列删除已排序行

Python 根据值计数列删除已排序行,python,pandas,Python,Pandas,我的数据框如下所示: year id 0 2019 x1 1 2012 x1 2 2017 x1 3 2013 x1 4 2018 x2 5 2012 x2 6 2013 x2 我想过滤我的整个数据帧,这样如果每个id有超过3个观察值,那么应该删除具有最低年份的观察值 year id 0 2019 x1 1 2017 x1 2 2013 x1 3 2018 x2 4 2012 x2 5

我的数据框如下所示:

   year   id    
0  2019   x1
1  2012   x1
2  2017   x1
3  2013   x1
4  2018   x2
5  2012   x2
6  2013   x2
我想过滤我的整个数据帧,这样如果每个id有超过3个观察值,那么应该删除具有最低年份的观察值

   year   id    
0  2019   x1
1  2017   x1
2  2013   x1
3  2018   x2
4  2012   x2
5  2013   x2
在这种情况下,应删除第1行

   year   id    
0  2019   x1
1  2017   x1
2  2013   x1
3  2018   x2
4  2012   x2
5  2013   x2
用于:

如果订单应相同,则添加:


使用
GroupBy.nlargest

df = df.groupby('id')['year'].nlargest(3).reset_index().drop(columns='level_1')

   id  year
0  x1  2019
1  x1  2017
2  x1  2013
3  x2  2018
4  x2  2013
5  x2  2012
确保
year
具有
int
d类型:

df['year'] = df['year'].astype(int)

使用for循环来解决这个问题怎么样(我喜欢for循环):


也许不是最快的,但创意+1。还有什么你喜欢的吗,给Loop Berry?谢谢你!我不得不说,没有什么比线圈更让我爱的了,但就在不久前,线圈还征服了我心中的一个小地方!
df['year'] = df['year'].astype(int)
id_unique = df.id.unique()

df_new = pd.DataFrame(columns = df.columns)

for i in id_unique:
    df_new = pd.concat([df_new, df[df['id'] == i ].sort_values(['year'], ascending= [False]).head(3)], axis=0)