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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With