[英]First pandas DataFrame column index greater than x
我知道將pandas DataFrame列轉換為列表(使用.tolist()
或list()
),然后執行您想要的操作,這會使它變慢得多,所以我不想使用這些方法 。
我想找到pandas DataFrame列的第一個元素的索引,該索引等於或大於值x
,換句話說>=x
。 如果沒有任何內容,則返回None
。
例如,如果列是this並且我們的函數稱為first_greater()
:
0
0 1
1 -5
2 6
3 4
4 -7
5 12
6 -2
7 0
8 -3
然后我們有:
first_greater(-5) = 0
first_greater(7) = 5
first_greater(4) = 2
first_greater(6) = 2
first_greater(22) = None
我是熊貓的新手,我也不知道該怎么做。 任何幫助,將不勝感激。
您既要檢查數據幀中的任何值是否大於給定值,又要返回滿足條件的第一個值。 您有idxmax
:
def first_greater(df, n, col):
m = df.col.ge(n)
return m.any() and m.idxmax()
請注意,在return語句中, and
的右邊部分僅在滿足第一個條件m.any()
時才求值,否則返回False
。
讓我們檢查建議的示例:
first_greater(df, 5, 'col1')
# 0
first_greater(df, 7, 'col1')
# 5
first_greater(df, 4, 'col1')
# 2
first_greater(df, 6, 'col1')
# 2
first_greater(df, 22, 'col1')
# False
輸入數據 -
col1
0 1
1 -5
2 6
3 4
4 -7
5 12
6 -2
7 0
8 -3
s = pd.Series([1, -5, 6, 4, -7, 12, -2, 0, -3])
def first_greater(n):
condition = (s >= n)
if condition.any():
return condition.idxmax()
else:
return None
我知道您已經有了答案。 但這只是展示可能性的另一種方法
def fg(n):
try:
a = df.loc[df.col1.ge(n)].index[0]
return a
except:
print('None')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.