Exclude certain columns of a data set in a 'for' loop

Question:

I currently am trying to perform a calculation on some of the columns in my data frame, this is a list of all the columns in my data frame.

>>> list(df)
['Time', 'England Apples', 'England Oranges', 'England Pears', 'England Apricots', 'England Watermelons', 'COAL', 'England Price', 'revenue', 'roll_rev_sum', 'roll_qty_sum']

However, in my for loop I don’t want to select the time variable so I do this:

for col in df.columns[1:-1]:

This works well, however now I also don’t want to include England Price in my calculation, in other words, I don’t want it to be one of the cols in my for loop.

How can I achieve this?

Asked By: user11015000

||

Answers:

You can drop a column (or even more) by its name:

for col in df.columns[1:-1].drop(['England Price']):
   print(col)
Answered By: JoergVanAken

To get a list of the columns you want, you can do

new_cols = [col for col in df.columns if col not in ['Time', 'England Price']]
Answered By: m13op22

Both the previous answers have something missing. Use:

for cols in df.drop(['Times', 'England Price'], axis=1):
    print(cols)

This will do.

Answered By: devansh Saini
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.