gpt4 book ai didi

python - 如何排除和过滤 Pandas 中的几列?

转载 作者:行者123 更新时间:2023-12-03 21:28:26 39 4
gpt4 key购买 nike

我知道我们只能使用 pandas 数据框过滤器选择几列,但我们也可以只排除一些列吗?

这是MWE:

import numpy as np
import pandas as pd


df = pd.DataFrame({'id': [1,2,3], 'num_1': [10,20,30], 'num_2': [20,30,40]})

df.filter(regex='num')

我们可以选择列中没有“num”的所有列:

就像是:
df.filter(regex='^(num)')

所需输出
   id
0 1
1 2
2 3

备注
# these already works, i am only looking regex way
df[['id']] # gives the required output


引用:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html

最佳答案

您可以获得没有 num 的列的列表使用列表理解

cols_without_num = [x for x in list(df) if 'num' not in x]

然后对数据进行子集化
df[cols_without_num]

关于python - 如何排除和过滤 Pandas 中的几列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009504/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com