Search code examples
pythonpandasstringdataframecontains

pandas dataframe - does filtering / selecting cols by String preserve order?


I have a use case where I have say 10 cols out of which 5 start with the string 'Region'. I need to get a resulting dataframe which only contains those cols (starting with string 'Region'). Not only that, I need to make sure the order is preserved (e.g. if in original df, the col order is 'Region 1', 'Region 2', 'Region 3' -- this should be preserved and not result in 'Region 3', 'Region 2', 'Region 1' instead).

Would following the 'accepted answer' for this question preserve the order or is there some other method to achieve that?

stackoverflow - find-column-whose-name-contains-a-specific-string


Solution

  • Two steps first use filter

    s=df.filter(like='Region')