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!
Asked
Active
Viewed 6,370 times
4

Jane Sully
- 3,137
- 10
- 48
- 87
-
1Possible duplicate of [Selecting columns](https://stackoverflow.com/questions/11285613/selecting-columns) – e4c5 Jun 12 '17 at 03:39
2 Answers
7
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.

piRSquared
- 285,575
- 57
- 475
- 624
0
A simple way would be to use slicing with iloc
all but last column would be:
df.iloc[:,:-1]
all but first column would be:
df.iloc[:,1:]

alex
- 1