Python 如何在列中查找行索引?
我对Python 如何在列中查找行索引?,python,pandas,Python,Pandas,我对pandas非常陌生,我试图为any值获取比lprice更高的行索引。有人能告诉我我做错了什么吗 数据帧 StrikePrice 0 40.00 1 50.00 2 60.00 3 70.00 4 80.00 5 90.00 6 100.00 7 110.00 8 120.00 9 130.00 10 140.00 11 150.00 12 160.00 13 17
pandas
非常陌生,我试图为any值获取比lprice
更高的行索引。有人能告诉我我做错了什么吗
数据帧
StrikePrice
0 40.00
1 50.00
2 60.00
3 70.00
4 80.00
5 90.00
6 100.00
7 110.00
8 120.00
9 130.00
10 140.00
11 150.00
12 160.00
13 170.00
14 180.00
15 190.00
16 200.00
17 210.00
18 220.00
19 230.00
20 240.00
现在,我正试图找出如何获得任何值的行索引
,该值高于lprice
lprice = 99
for strike in df['StrikePrice']:
strike = float(strike)
# print(strike)
if strike >= lprice:
print('The high strike is:' + str(strike))
ce_1 = strike
print(df.index['StrikePrice' == ce_1])
上面给出了0
作为索引
我不确定我在这里做错了什么。在布尔切片后使用索引属性
lprice = 99
df[df.StrikePrice >= lprice].index
Int64Index([6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], dtype='int64')
如果在找到代码时坚持迭代和查找,则可以修改代码:
lprice = 99
for idx, strike in df['StrikePrice'].iteritems():
strike = float(strike)
# print(strike)
if strike >= lprice:
print('The high strike is:' + str(strike))
ce_1 = strike
print(idx)
我认为最好的过滤指标是:
您的代码应进行类似更改:
lprice = 99
for strike in df['StrikePrice']:
if strike >= lprice:
print('The high strike is:' + str(strike))
print(df.index[df['StrikePrice'] == strike])
如果我们仅指定条件
,则会执行此操作
np.where()
返回元组
condition.nonzero()
,如果只给出了条件
,则其中条件
的索引为True
In [36]: np.where(df.StrikePrice >= lprice)[0]
Out[36]: array([ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], dtype=int64)
PS感谢--np.where()
返回数值索引位置,而不是DF索引值:
In [41]: df = pd.DataFrame({'val':np.random.rand(10)}, index=pd.date_range('2018-01-01', freq='9999S', periods=10))
In [42]: df
Out[42]:
val
2018-01-01 00:00:00 0.459097
2018-01-01 02:46:39 0.148380
2018-01-01 05:33:18 0.945564
2018-01-01 08:19:57 0.105181
2018-01-01 11:06:36 0.570019
2018-01-01 13:53:15 0.203373
2018-01-01 16:39:54 0.021001
2018-01-01 19:26:33 0.717460
2018-01-01 22:13:12 0.370547
2018-01-02 00:59:51 0.462997
In [43]: np.where(df['val']>0.5)[0]
Out[43]: array([2, 4, 7], dtype=int64)
解决方法:
In [44]: df.index[np.where(df['val']>0.5)[0]]
Out[44]: DatetimeIndex(['2018-01-01 05:33:18', '2018-01-01 11:06:36', '2018-01-01 19:26:33'], dtype='datetime64[ns]', freq=None)
到目前为止,您的两个答案都是基于列对数据帧进行切片,然后获取索引。这篇文章也可能有用@谢谢,这个链接将非常有用。谢谢。是否可以在上面的代码中获取索引值,即仅为迭代的值获取索引值?我需要使用相同的方法从不同的列中获取相应的值。我更新了我的帖子。希望这能回答你的问题。
In [44]: df.index[np.where(df['val']>0.5)[0]]
Out[44]: DatetimeIndex(['2018-01-01 05:33:18', '2018-01-01 11:06:36', '2018-01-01 19:26:33'], dtype='datetime64[ns]', freq=None)