Reputation: 490
I have a dataframe which is something like this
Victim Sex Female Male Unknown
Perpetrator Sex
Female 10850 37618 24
Male 99354 299781 92
Unknown 33068 156545 148
I'm planning to drop both the row indexed as 'Unknown'
and the column named 'Unknown
'. I know how to drop a row and a column but I was wondering whether you could drop a row and a column at the same time in pandas? If yes, how could it be done?
Upvotes: 3
Views: 4296
Reputation: 1043
You can delete columns and rows at the same time in one line just with their position. For example, if you want delete column 2,3 and 5 and at the same time if you want to remove index 0,1 and 3 along with the last row of the dataframe, you can do this by following,
df.drop(df.columns[[2,3,5]], axis = 1).drop(df.index[[0,1,3,-1]])
Upvotes: 3
Reputation: 863196
I think closest 'at the same time'
is select by loc
and difference
:
print (df.index.difference(['Unknown']))
Index(['Female', 'Male'], dtype='object')
print (df.columns.difference(['Unknown']))
Index(['Female', 'Male'], dtype='object')
df = df.loc[df.index.difference(['Unknown']), df.columns.difference(['Unknown'])]
print (df)
Victim Sex Female Male
Perpetrator Sex
Female 10850 37618
Male 99354 299781
Upvotes: 5
Reputation: 5437
This should do the job, however it's not really at the same time, but no intermediate object is returned to you.
df.drop("Unknown", axis=1).drop("Unknown", axis=0)
So for a concrete Example:
df = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B'], index=['C','D'])
print(df)
A B
C 1 2
D 3 4
the call
df.drop('B', axis=1).drop('C', axis=0)
returns
A
D 3
Upvotes: 6