Select Pandas Rows By Excluding Index Number
Not quite sure why I can't figure this out.  I'm looking to slice a Pandas dataframe by using index numbers.   I have a list/core index with the index numbers that i do NOT need, s
Solution 1:
Not sure if that's what you are looking for, posting this as an answer, because it's too long for a comment:
In [31]: d = {'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6]}
In [32]: df = pd.DataFrame(d)
In [33]: bad_df = df.index.isin([3,5])
In [34]: df[~bad_df]
Out[34]: 
   a  b
0  1  1
1  2  2
2  3  3
4  5  5
Solution 2:
Just use .drop and pass it the index list to exclude.
import pandas as pd
df = pd.DataFrame({"a": [10, 11, 12, 13, 14, 15]})
df.drop([1, 2, 3], axis=0)
Which outputs this.
    a
0  10
4  14
5  15
Solution 3:
Probably an easier way is just to use a boolean index, and slice normally doing something like this:
df[~df.index.isin(list_to_exclude)]
Solution 4:
You could use pd.Int64Index(np.arange(len(df))).difference(index) to form a new ordinal index. For example, if we want to remove the rows associated with ordinal index [1,3,5], then
import numpy as np
import pandas as pd
index = pd.Int64Index([1,3,5], dtype=np.int64)
df = pd.DataFrame(np.arange(6*2).reshape((6,2)), index=list('ABCDEF'))
#     0   1
# A   0   1
# B   2   3
# C   4   5
# D   6   7
# E   8   9
# F  10  11
new_index = pd.Int64Index(np.arange(len(df))).difference(index)
print(df.iloc[new_index])
yields
   0  1
A  0  1
C  4  5
E  8  9
Post a Comment for "Select Pandas Rows By Excluding Index Number"