Prana Prana - 1 month ago 5
Python Question

How to keep one single column as a dataframe

I have dataframe with 20 columns and one index.

Its shape is something like (100, 20).

I want to slice the 3rd column from this dataframe, but want to keep the result as a dataframe of (100,1).

  1. If I do a
    v = df['col3']
    , I get a Series (which I do not want)

  2. If I do a
    v =df[df['col3']!=0]
    and then
    v.drop(label=[list of 19 columns], axis = 1)
    --- I get what I want [that is a df(100,1)] but I have to

(a) write an unnecessary != condition ( which I want to avoid) and

(b) I have to write a long list of 19 column names.

There should be a better and cleaner way of doing what I wan to achieve.


Another handy trick is to_frame()