没有合适的资源?快使用搜索试试~ 我知道了~
Python Pandas 获取列匹配特定值的行的索引问题
5星 · 超过95%的资源 7 下载量 80 浏览量
2020-12-26
00:42:49
上传
评论
收藏 95KB PDF 举报
温馨提示
试读
2页
给定一个带有列”BoolCol”的DataFrame,如何找到满足条件"BoolCol" == True的DataFrame的索引 目前有迭代的方式来做到这一点: for i in range(100,3000): if df.iloc[i]['BoolCol']== True: print i,df.iloc[i]['BoolCol'] 这虽然可行,但不是标准的 Pandas 方式。经过一番研究,我目前正在使用这个代码: df[df['BoolCol'] == True].index.tolist() 这个给了我一个索引列表,但跟我想要的不匹配,当检查: df.iloc[i]
资源推荐
资源详情
资源评论
Python Pandas 获取列匹配特定值的行的索引问题获取列匹配特定值的行的索引问题
给定一个带有列”BoolCol”的DataFrame,如何找到满足条件"BoolCol" == True的DataFrame 的索引
目前有迭代的方式来做到这一点:
for i in range(100,3000):
if df.iloc[i]['BoolCol']== True:
print i,df.iloc[i]['BoolCol']
这虽然可行,但不是标准的 Pandas 方式。经过一番研究,我目前正在使用这个代码:
df[df['BoolCol'] == True].index.tolist()
这个给了我一个索引列表,但跟我想要的不匹配,当检查:
df.iloc[i]['BoolCol']
其结果实际上是False!
如何使用正确的 Pandas 方式做到这一点?
最佳解决方法最佳解决方法
df.iloc[i]返回df的第i行。 i不引用索引标签,i是从0开始的索引。
相反,属性index返回实际的索引标签,而不是数字row-indices:
df.index[df['BoolCol'] == True].tolist()
或者等同地,
df.index[df['BoolCol']].tolist()
通过使用带有”unusual”索引的DataFrame,可以非常清楚地看到差异:
df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
index=[10,20,30,40,50])
In [53]: df
Out[53]:
BoolCol
10 True
20 False
30 False
40 True
50 True
[5 rows x 1 columns] In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]
如果你想使用索引,
In [56]: idx = df.index[df['BoolCol']] In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')
那么您可以使用loc而不是iloc选择行:
In [58]: df.loc[idx] Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
请注意,loc也可以接受布尔数组:
In [55]: df.loc[df['BoolCol']] Out[55]:
BoolCol
10 True
40 True
50 True
weixin_38557896
- 粉丝: 0
- 资源: 971
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页