question.it
question.it

Reputation: 2978

How to remove entire column from data frame if column name is nan, Python 3.6

I have data frame with 15 columns & some column name is nan, How to delete if column name is nan.

columns:

['Country', 'Survey', 'a typical day', 'a particularly good day',
   'a particularl', 'dk/refused', 'total', nan, nan, nan, nan, nan,
   'questionsCode'], dtype=object)

Expected data frame with below columns:

['Country', 'Survey', 'a typical day', 'a particularly good day',
   'a particularl', 'dk/refused', 'total', questionsCode'], dtype=object)

Upvotes: 0

Views: 188

Answers (1)

piRSquared
piRSquared

Reputation: 294576

Setup
Consider the sample dataframe df

cols = [
    'Country', 'Survey', 'a typical day',
    'a particularly good day', 'a particularl',
    'dk/refused', 'total',
    np.nan, np.nan, np.nan, np.nan, np.nan,
   'questionsCode'
]

df = pd.DataFrame([range(13)], range(2), cols)
df

   Country  Survey  a typical day  a particularly good day  a particularl  dk/refused  total  NaN  NaN  NaN  NaN  NaN  questionsCode
0        0       1              2                        3              4           5      6    7    8    9   10   11             12
1        0       1              2                        3              4           5      6    7    8    9   10   11             12

Solution 1
Leverage loc with label based indexing

df.loc[:, df.columns.dropna()]

   Country  Survey  a typical day  a particularly good day  a particularl  dk/refused  total  questionsCode
0        0       1              2                        3              4           5      6             12
1        0       1              2                        3              4           5      6             12

This would've also worked

df[df.columns.dropna()]

Solution 2
Use Boolean indexing

df.loc[:, df.columns.notnull()]

   Country  Survey  a typical day  a particularly good day  a particularl  dk/refused  total  questionsCode
0        0       1              2                        3              4           5      6             12
1        0       1              2                        3              4           5      6             12

Upvotes: 2

Related Questions