从panda Datafram中的特定值获取索引

2024-09-26 22:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,从Dataframe列中的特定条目中获取行索引。我需要它,以便我可以使用该索引获取该条目所在的整行。我已经获得了我在列中寻找的值,但是我无法获得它的索引。以下是我目前的代码:

import glob, os
from pandas import *
filepath = r'C:\Users\Dani\Documents\clase dani\PhD\GC\Cuanti'
for csv_file in glob.glob(os.path.join(filepath, '*.csv')):
    rt=pandas.read_csv(csv_file, skiprows=6)
    rt.set_index('Peak')
    RTlist=rt.loc[:,'R.T.']
    for item in RTlist:
        if 5.5<item<5.8:
            #here's where I want to get the row index where item is at, but I can't achieve it. 

谢谢你的帮助


Tags: csvinimportpandasforindexos条目
2条回答

出于演示目的,我创建了源数据帧(rt),如下所示:

rt = pd.DataFrame([ [ 1, 2, 5 ], [ 2, 5, 6 ], [ 3, 5.52, 7 ], [ 4, 5.6, 8 ],
    [ 5, 5.75, 9 ], [ 6, 5.8, 10 ], [ 7, 6, 11 ] ],
    columns=[ 'Peak', 'R.T.', 'Xxx' ])
rt.set_index('Peak')

您可以使用单个指令获得结果(索引/值对):

rt['R.T.'][rt['R.T.'].between(5.5, 5.8, inclusive=False)]

对于我的测试数据,它打印:

2    5.52
3    5.60
4    5.75

rt['R.T.']选择整个'R.T.'

那么[rt['R.T.'].between(5.5, 5.8, inclusive=False)]是一个谓词, 选择指定范围内的值

或者您可能只对索引值感兴趣? 如果是这种情况,请写下:

rt[rt['R.T.'].between(5.5, 5.8, inclusive=False)].index

使用iteritems在系列RTlist中循环,这可能是您想要的

for index, item in RTlist.iteritems():
    if 5.5<item<5.8:
        item_index = index
        item_value = item

相关问题 更多 >

    热门问题