Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over all but last column in pandas dataframe + indexing?

Let's day I have a pandas dataframe df where the column names are the corresponding indices, so 1, 2, 3,....len(df.columns). How do I loop through all but the last column, so one before len(df.columns). My goal is to ultimately compare the corresponding element in each row for each of the columns with that of the last column. Any code with be helpful! Thank you!

like image 354
Jane Sully Avatar asked Mar 09 '23 21:03

Jane Sully


1 Answers

To iterate over each column, use

for column_name, column_series in df.iteritems():
     pass

To iterate over all but last column

for column_name, column_series in df.iloc[:, :-1].iteritems():
     pass

I'd highly recommend asking another question with more detail about what you are trying do to as it is likely we can avoid using the iterators completely via vectorization.

like image 80
piRSquared Avatar answered May 08 '23 20:05

piRSquared