Dropping columns before a matching string in the following column

Question:

Is there direct possibility to drop all columns before a matching string in a pandas Dataframe. For eg. if my column 8 contains a string ‘Matched’ I want to drop columns 0 to 7 ?

Asked By: Sherwin R

||

Answers:

Well, you did not give any information where and how to look for ‘Matched’, but let’s say that integer col_num contains the number of the matched column:

col_num = np.where(df == 'Matched')[1][0]
df.drop(columns=df.columns[0:col_num],inplace=True)

will do the drop

Answered By: gtomer

Example

data = {'A': {0: 1}, 'B': {0: 2}, 'C': {0: 3}, 'Match1': {0: 4}, 'D': {0: 5}}
df = pd.DataFrame(data)

df

    A   B   C   Match1  D
0   1   2   3   4       5

Code

remove in front of first Match + @ column : boolean indexing

df.loc[:, df.columns.str.startswith('Match').cumsum() > 0]

result

    Match1  D
0   4       5
Answered By: Panda Kim
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.