本文说明如何利用Pandas获得符合条件的数据的行/列索引值。
Updated: 2022/3/12


Python | Pandas | 获取行/列索引


获取行索引

根据列标签和指定的列的值,获取符合条件的数据所在的行的行索引1

  • 导入原始数据及获取其行/列标签

此处无法给出作者手中使用的原始数据。请使用自己手中的原始数据来做实验。

比如,⬇️

filepath = '.\\2022-02-25'
data = pd.read_excel(filepath, sheet_name='data')
'''
data.columns
# Index(['logged', 'updated', 'head', 'project', 'Hrs'], dtype='object')

data.index
# RangeIndex(start=0, stop=58, step=1)
'''
  • 根据列标签及相应的值,获取其所在的行索引
  • head列中值为High的数据所在的行(包括head列)
headHighVal = data.loc[data['head']=='High', ['head']]
'''
headHighVal
#     head
# 4   High
# 5   High
# ......
# 50  High
# 54  High

headHighVal.columns
# Index(['head'], dtype='object')

headHighVal.index
# Int64Index([4, 5, 16, 17, 21, 22, 23, 26, 42, 46, 47, 50, 54], dtype='int64')
'''
  • head列中值为High的数据所在的行(包括所有列)
headHighVals = data.loc[data['head'] == 'High']
'''
headHighVals
#                           logged  ... 		 Hrs
# 4   2022-02-18T13:44:22.216+0800  ...          4.0
# 5   2022-02-18T13:45:11.866+0800  ...         16.0
......
# 50  2022-02-24T15:58:30.605+0800  ...          1.0
# 54  2022-02-23T11:12:54.924+0800  ...          2.0
#
# [13 rows x 12 columns]

headHighVals.columns
# Index(['logged', 'updated', 'head', 'project', 'Hrs'], dtype='object')

headHighVals.index
# Int64Index([4, 5, 16, 17, 21, 22, 23, 26, 42, 46, 47, 50, 54], dtype='int64')
'''
  • head列中值为Highproject列中值为P的数据所在的行(包括headproject列)
headprj = data.loc[(data['head']=='High') & (data['project']=='P'),['head','project']]
'''
headprj
#     head  project
# 4   High  	  P
# 5   High  	  P
# 42  High  	  P
# 46  High  	  P
# 47  High  	  P
# 50  High  	  P

headprj.columns
# Index(['head', 'project'], dtype='object')

headprj.index
# Int64Index([4, 5, 42, 46, 47, 50], dtype='int64')
'''

参考链接


  1. python pandas查找DataFrame中指定数据的索引 ↩︎

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐