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?
Answers:
You can drop a column (or even more) by its name:
for col in df.columns[1:-1].drop(['England Price']):
print(col)
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']]
Both the previous answers have something missing. Use:
for cols in df.drop(['Times', 'England Price'], axis=1):
print(cols)
This will do.
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?
You can drop a column (or even more) by its name:
for col in df.columns[1:-1].drop(['England Price']):
print(col)
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']]
Both the previous answers have something missing. Use:
for cols in df.drop(['Times', 'England Price'], axis=1):
print(cols)
This will do.