繁体   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