[英]How do you reference the index of the column in a for-loop?
Hi sorry I'm new to Pandas.嗨,对不起,我是 Pandas 的新手。 I was wondering how to input the index of whatever column I am trying to perform the function on.
我想知道如何输入我试图执行该功能的任何列的索引。 I tried
df[column].index
but I keep getting IndexError
on those lines I use it in.我尝试了
df[column].index
但在我使用它的那些行上不断收到IndexError
。
For context I am trying to find the index at which a certain value (-10) is passed for each column which is cd
.对于上下文,我试图找到为
cd
的每一列传递某个值(-10)的索引。 Then I have to interpolate it to find the exact value at which -10 occurs which is cd10
.然后我必须对其进行插值以找到发生 -10 的确切值,即
cd10
。
Thank you so much in advance!非常感谢您!
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)
I cannot reproduce your code as I do not fully understand how your dataframe is structured and I did not fully understand the interpolation part but I would try to suggest a solution to your problem purely from your description.我无法重现您的代码,因为我不完全了解您的数据框的结构,也没有完全理解插值部分,但我会尝试仅根据您的描述提出解决问题的方法。
From the description I guess that you want to get the numeric index of a column from column name.从描述中我猜你想从列名中获取列的数字索引。 Please correct me if I am wrong and the interpolation is a significant part of the question.
如果我错了,请纠正我,插值是问题的重要部分。
You can do it by converting the column index of the dataframe to a list.您可以通过将数据框的列索引转换为列表来实现。
for column in df.columns[1:]:
column_index = df.columns.tolist().index(column)
print(f'column index of {column} is {column_index}')
Another option which looks more pythonic to me would be to enumerate the columns:另一个对我来说看起来更 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.