选择/排除 pandas 中的列集 [英] Selecting/excluding sets of columns in pandas
本文介绍了选择/排除 pandas 中的列集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据列选择从现有数据框中创建视图或数据框.
I would like to create views or dataframes from an existing dataframe based on column selections.
例如,我想从一个数据框df1
创建一个数据框df2
,该数据框保存其中的所有列,除了其中的两列.我尝试执行以下操作,但没有成功:
For example, I would like to create a dataframe df2
from a dataframe df1
that holds all columns from it except two of them. I tried doing the following, but it didn't work:
import numpy as np
import pandas as pd
# Create a dataframe with columns A,B,C and D
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
# Try to create a second dataframe df2 from df with all columns except 'B' and D
my_cols = set(df.columns)
my_cols.remove('B').remove('D')
# This returns an error ("unhashable type: set")
df2 = df[my_cols]
我做错了什么?也许更笼统地说,大熊猫必须采用什么机制来支持从数据框中挑选和排除排除任意列?
What am I doing wrong? Perhaps more generally, what mechanisms does pandas have to support the picking and exclusions of arbitrary sets of columns from a dataframe?
推荐答案
您可以删除不需要的列,也可以选择所需的列
You can either Drop the columns you do not need OR Select the ones you need
# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)
# Select the ones you want
df1 = df[['a','d']]
这篇关于选择/排除 pandas 中的列集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文