简体   繁体   中英

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

Hi sorry I'm new to 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.

For context I am trying to find the index at which a certain value (-10) is passed for each column which is cd . Then I have to interpolate it to find the exact value at which -10 occurs which is 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM