1

I want to drop multiple columns(around 800) from the dataframe using python. I have written below code:

  def corr_df(x, corr_val):


    # Creates Correlation Matrix and Instantiates
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []
    df_drop=pd.DataFrame()
    cols=[]
    # Iterates through Correlation Matrix Table to find correlated columns
    for i in iters:
        for j in range(i):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = item.values
            if val >= corr_val:
                # Prints the correlated feature set and the corr val
                #print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(i)

    drops = sorted(set(drop_cols))[::-1]
    df_dropped=x.drop(drops,axis=1)
    # Drops the correlated columns
#     for i in drops:
#         col=(x.iloc[:, (i+1):(i+2)].columns.values.tolist())
#         print (col)
#         df_dropped=df.drop(col, axis=1)

        #cols.append()

    #print(df_dropped)
    return (df_dropped)

But this code is printing the dataframe have only one column dropped. Any comments or suggestions on this?

Thanks in advance

6
  • 2
    Use df = df.drop(lst, axis=1), where lst is your list of columns. Is there a reason why you need to perform this one at a time iteratively? Commented Feb 5, 2018 at 18:58
  • I can drop all of them once, but when I am doing the df.drop(drops,axis=1). Getting ValueError: labels [1069 1068 1067 ..., 3 2 1] not contained in axis. Commented Feb 5, 2018 at 19:03
  • that means the columns don't exist for you to drop them. Commented Feb 5, 2018 at 19:04
  • Yup, But columns are there. I don't why it is throwing valueError. Commented Feb 5, 2018 at 19:05
  • @jp_data_analysis, I have added full code, please have a look. Commented Feb 5, 2018 at 19:06

1 Answer 1

1

Drop multiple columns by numerical index like this:

cols = [1069, 1068, 1067]

df = df.drop(df.columns[cols], axis=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.