[英]How to compare given value with Pandas dataframe values without using a for loop
我有以下示例 dataframe:
d = {'target': [1, 2, 4, 3, 6, 5]}
df = pd.DataFrame(data=d)
df
Output:
target
0 1
1 2
2 4
3 3
4 6
5 5
我需要一個 function 來執行以下操作:
讓 function 的名稱為find_index_of_first_hit(value)
。
function...
value
與列target
的元素進行比較。value
。index
。例子:
find_index_of_first_hit(3)
應該返回2
,它是target
列值 4 的索引,這是列值(即 4)>= function 輸入值 3 在該列中第一次出現的位置。 而index為2,預計會返回。
原來的 dataframe 相當大,我想知道如何在不使用 for 循環的情況下編寫這樣的程序。
這個 function 需要寫成 Python 並且它需要是一個快速的解決方案,這就是為什么我想避免 for 循環。 性能在這里很重要。
我怎么能寫這樣的 Python function 做這個工作?
使用Series.idxmax
測試是否值存在於if-else
和Series.any
:
def find_index_of_first_hit(val):
a = df['target'].ge(val)
return a.idxmax() if a.any() else -1
print (find_index_of_first_hit(3))
2
print (find_index_of_first_hit(30))
-1
使用等式檢查.eq
和idxmax
您會發現您很少需要為 Pandas 編寫任何函數(除非您需要 package 編寫可重復使用的代碼片段),因為大部分內容都在 API 中可用。
index = df.ge(3).idxmax()
target 2
dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.