Pandas:如何获取除与给定列表匹配的列名之外的列名

2024-05-23 22:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个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

如何获取所有列名,但排除名称与daypurchase、&cost


Tags: 名称appledataframedfrangepurchasepdpear
2条回答

使用:

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

或:

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

df = df[cols]

通过列表理解

cols = [i for i in df.columns if i not in ["day", "purchase", "cost"]]

相关问题 更多 >