簡體   English   中英

你如何在 for 循環中引用列的索引?

[英]How do you reference the index of the column in a for-loop?

嗨,對不起,我是 Pandas 的新手。 我想知道如何輸入我試圖執行該功能的任何列的索引。 我嘗試了df[column].index但在我使用它的那些行上不斷收到IndexError

對於上下文,我試圖找到為cd的每一列傳遞某個值(-10)的索引。 然后我必須對其進行插值以找到發生 -10 的確切值,即cd10

非常感謝您!

for column in df.columns[1:]:
    cd = HERdf.loc[df.iloc[: , df[column].index] <= -10].index[0]
    cd10 = np.interp(x = -10 , xp = df.iloc[cd-1:cd+2 , df[column].index] , fp = df.iloc[cd-1:cd+2 , 0] )
    print (cd10)

我無法重現您的代碼,因為我不完全了解您的數據框的結構,也沒有完全理解插值部分,但我會嘗試僅根據您的描述提出解決問題的方法。

從描述中我猜你想從列名中獲取列的數字索引。 如果我錯了,請糾正我,插值是問題的重要部分。

您可以通過將數據框的列索引轉換為列表來實現。

for column in df.columns[1:]:
    column_index = df.columns.tolist().index(column)
    print(f'column index of {column} is {column_index}')

另一個對我來說看起來更 Pythonic 的選項是枚舉列:

for column_index, column in enumerate(df.columns[1:], start=1):
    print(f'column index of {column} is {column_index}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM