python-3.x - 从数据框中的列表中过滤列的最佳方法

标签 python-3.x pandas dataframe

只是想采用不同的方法来获取与 pandas 中的 df.columns 匹配/过滤的列表。

下面的代码片段工作完美,但期待其他方法。 即使我们可以考虑一个函数,请原谅我的简洁,因为我只是在学习 pandas。

# list of columns names to be matched & checked
>>> matchObj = ['equity01',  'equity02',  'equity1'  'equity2']

# DataFrame construct
>>> df = pd.DataFrame({'equity01': [1, 2, 3], 'equity02': [4, 5, 6], 'equity03': [7, 8, 9], 'equity04': [2, 3, 4], 'equity05': [5, 6, 7]})
>>> df
   equity01  equity02  equity03  equity04  equity05
0         1         4         7         2         5
1         2         5         8         3         6
2         3         6         9         4         7

# One way to  with list comprehension as follows..
>>> print(df[[col for col in matchObj if col in df.columns]])
   equity01  equity02
0         1         4
1         2         5
2         3         6

提前感谢您提供的任何建议和解决方案。

最佳答案

是的,使用 pd.Index.intersection() :

df[df.columns.intersection(matchObj)]

   equity01  equity02
0         1         4
1         2         5
2         3         6

关于python-3.x - 从数据框中的列表中过滤列的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029587/

相关文章:

python - 使用 pandas 将字符串列连接到新列时出现问题吗?

python-3.x - Flask-security 创建角色、用户并将 user_id 链接到 role_id

Python:在列表中创建换行符以便 openpyxl 在 .xlsx 中识别

python - 如何使用多部分seaborn图迭代填充matplotlib gridspec?

带和不带 lambda 的 pandas apply()

python - 根据优先级在 Pandas 数据框中创建二进制列

python - matplot lib "fatal IO error 25 (Inappropriate ioctl for device) on X server "localhost :10. 0“

scala - 如何从 DataFrame 中选择案例类中存在的列

python - Python 中 DataFrame 中数组值的 One-hot 编码

Python - 获取每周、每月、每季度、六个月、每年等的第一个和最后一个观察结果