Issue
I am trying to drop some columns but I wanted to set a variable which numbers the columns I would like to drop instead of hard-coding it.
My Code is:
import pandas as pd
import numpy as np
df = pd.read_csv(WorkdayExcelPathName,low_memory=(False))
ColumnsToDrop = df.iloc[:, [57,125]]
df2 = df.drop(df.columns[ColumnsToDrop], axis = 1)
print(df2)
which gives me this error:
IndexError: only integers, slices (
:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices
I have also tried using:
ColumnsToDrop = df.iloc[:, np.r_[57,125]]
But it continues to produce the same IndexError error.
what am I doing wrong?
Solution
try this instead
df.drop(df.columns[[57, 125]], axis=1)
or this if you want it to look more like what you already have
ColumnsToDrop = df.iloc[:, [57, 125]].columns
df2 = df.drop(ColumnsToDrop, axis=1)
Answered By - karim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.