首页 > 解决方案 > Pandas:使用 loc 获取固定数量的行

问题描述

假设我们有以下 Dataframe。

tempDataframe = 

Col1 Col2
1   2
1   4
2   5

运行以下代码后,我期望得到这个结果:

tempDataframe = tempDataframe.set_index('Col1')
tempDataframe.loc[[1,2]]

Col1 Col2
1    2
1    4
2    5
2    0

对于每个索引,应该至少有两个结果。对于少于两个值的条目,应返回一个带零的额外条目。

标签: pythonpandas

解决方案


在您的情况下,您需要使用创建一个辅助键cumcount

df['New']=df.groupby(level=0).cumcount()
df.set_index('New',append=True,inplace=True)
df.unstack(fill_value=0).stack().groupby(level=0).head(2)
Out[436]: 
          Col2
Col1 New      
1    0       2
     1       4
2    0       5
     1       0

推荐阅读