python - 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
对于每个索引,应该至少有两个结果。对于少于两个值的条目,应返回一个带零的额外条目。
解决方案
在您的情况下,您需要使用创建一个辅助键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
推荐阅读
- android - 插页式视频广告显示后 Exoplayer 播放错误
- android - 没有“请勿打扰”的静音电话
- javascript - 使用返回的 id 创建的文档但在数据库 Firebase 和 Vue.js 中找不到
- android-studio - 如何在 Kotlin 中的按钮前面显示图像视图?
- amazon-web-services - 当只有 1 个 IAM 用户可以访问 S3 存储桶时,我是否需要启用公共访问?
- c++ - 二进制“=”:未找到采用右手操作数的运算符(或没有可接受的对话)
- java - 我需要将此休眠表表示为 mysql 表
- ios - 使用 iwatch 快速提取心率代码
- plot - 从最近的错误值绘制时间序列价格范围日期与日期时间框架不匹配
- shinyapps - 如何为闪亮的应用程序制作安装文件?