Home > front end >  How to drop a user specified multiple columns from a DataFrame in Python?
How to drop a user specified multiple columns from a DataFrame in Python?

Time:10-17

##Drop the unwated columns

def drop_columns(df):
    s_col= [item for item in input("Enter the list items : ").split()]
    try:
        [df.drop(i, axis=1, inplace= True) for i in range(len(s_col))]
        print("Column {} has been found and removed.".format(s_col))
    except:
        print("Column {} does not exist.\nNo columns have been removed.".format(s_col))
    print(df.info())

CodePudding user response:

IIUC, you can use:

def drop_columns(df):
    to_del = input("Enter the list items : ").split()
    print(f'will delete: {", ".join(df.columns.intersection(to_del))}')
    invalid = set(to_del)-set(df.columns)
    if len(invalid)>0:
        print(f'input {", ".join(invalid)} is invalid')
    df.drop(columns=df.columns.intersection(to_del),
            inplace=True, errors='ignore')
    
df = pd.DataFrame([['X', 'Y', 'Z']], columns=['A', 'B', 'C'])
print(df)
drop_columns(df)

print(df)

Example:

   A  B  C
0  X  Y  Z
Enter the list items : B D E
will delete: B
input E, D is invalid
   A  C
0  X  Z

CodePudding user response:

Try adding the below part: [df.drop(s_col(i), axis=1, inplace= True) for i in range(len(s_col))]

  • Related