-1

Assume I have a df:

df = pd.DataFrame({'day': range(1, 4),
                  'apple': range(5, 8),
                  'orange': range(7, 10),
                  'pear': range(9, 12),
                  'purchase': [1, 1, 1],
                  'cost': [50, 55, 60]})

day   apple   orange   pear   purchase   cost
1     5       7        9      1          50
2     6       8        10     1          55
3     7       9        11     1          60

How do I get all column names but exclude those which name matches day, purchase, & cost?

Agnes Lee
  • 322
  • 1
  • 12
  • 2
    Does this answer your question? [How to select all columns, except one column in pandas?](https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-column-in-pandas) – Shradha Jun 29 '21 at 05:54

2 Answers2

3

Use:

cols = df.columns.difference(['day', 'purchase', 'cost'], sort=False)

Or:

cols = df.columns[~df.columns.isin(['day', 'purchase', 'cost'])]

df = df[cols]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

Via list comprehension

cols = [i for i in df.columns if i not in ["day", "purchase", "cost"]]
crayxt
  • 2,367
  • 2
  • 12
  • 17