0

I have a dataframe with columns similar to

Run  Date1  Date2  Date3  A.0  A.1  A.2  B.0  B.1  B.2....

I want to keep the Run and Date columns but only select the columns that contain A, B, etc. So the output should look something like

Run  Date1  Date2  Date3  A.0  A.1  A.2 

Using filter(like=A, axis=1) only gives me columns with A and not the run and date columns

I tried

df.iloc[:, [0,1,2,3,df.columns.get_loc(df.columns.str.contains("A"))]]

but it says a boolean list is not a valid key

3
  • You could set Run Date1 Date2 and Date2 in the index, then use filter. Commented Sep 30, 2019 at 15:19
  • df.filter(regex='Run|Date|A\.')? Commented Sep 30, 2019 at 15:23
  • This selects the Run and Date columns but none of the others Commented Sep 30, 2019 at 16:06

1 Answer 1

1

try this

cols = ["Run", "Date1", "Date2", "Date3"] + [col for col in df.columns if col.startswith["A"] or col.startswith["B"]]

df.loc[:, cols]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.