Extracting specific selected columns to new DataFrame as a copy

前端 未结 7 1937
忘了有多久
忘了有多久 2020-12-04 04:59

I have a pandas DataFrame with 4 columns and I want to create a new DataFrame that only has three of the columns. This question is similar

7条回答
  •  借酒劲吻你
    2020-12-04 05:20

    There is a way of doing this and it actually looks similar to R

    new = old[['A', 'C', 'D']].copy()
    

    Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

    An alternative method is to use filter which will create a copy by default:

    new = old.filter(['A','B','D'], axis=1)
    

    Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

    new = old.drop('B', axis=1)
    

提交回复
热议问题