Selecting multiple columns in a pandas dataframe

后端 未结 19 1791
醉话见心
醉话见心 2020-11-22 00:08

I have data in different columns but I don\'t know how to extract it to save it in another variable.

index  a   b   c
1      2   3   4
2      3   4   5
         


        
19条回答
  •  执笔经年
    2020-11-22 00:08

    The different approaches discussed in above responses are based on the assumption that either the user knows column indices to drop or subset on, or the user wishes to subset a dataframe using a range of columns (for instance between 'C' : 'E'). pandas.DataFrame.drop() is certainly an option to subset data based on a list of columns defined by user (though you have to be cautious that you always use copy of dataframe and inplace parameters should not be set to True!!)

    Another option is to use pandas.columns.difference(), which does a set difference on column names, and returns an index type of array containing desired columns. Following is the solution:

    df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'],index=[1,2])
    columns_for_differencing = ['a']
    df1 = df.copy()[df.columns.difference(columns_for_differencing)]
    print(df1)
    

    The output would be: b c 1 3 4 2 4 5

提交回复
热议问题