0

I'm trying to make my code more elegant and I realized I may be doing some unnecessary coding. I have many variables entitled things like trust_1, trust_2, trust_3, etc. up to 25. I'm creating a new data frame made up of these variables in pandas.

df = df1[['trust_1', 'trust_2', 'trust_3', 'trust_4', 'trust_5' ]]

I was wondering if I could use regular expressions or something that takes the place of the number and will keep all the variables. For example,

df = df1[['trust_\d+']] 

that would do the same thing as above. Is there a way?

ayhan
  • 70,170
  • 20
  • 182
  • 203
ascott
  • 11
  • Don't store everything in variables, use a data structure that's more appropriate. – Joe Iddon Jan 25 '18 at 21:14
  • You can use `df.filter(like='trust')` or one of the many alternatives listed in the dupe. `.filter` also accepts regex. Check the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html) – ayhan Jan 25 '18 at 21:15

0 Answers0