Reputation: 1251
I'm trying to filter my columns in dataframe that contain the letters "R" or "H".
The code works when I only search for 1 of the letters but it's returning all the columns when I add an or
statement.
I was wondering if it was possible to use the or in a list comprehension. Here is my code:
data = pd.read_csv(filename)
data_sorted = data.sort_values('Timestamp', ascending=False)
four_dec_cols = [col for col in data_sorted if 'H' in col]
failed code:
four_dec_cols = [col for col in data_sorted if 'RB' or 'H' in col]
Utlimately, I want to round the columns that contain 'H' or 'R' to 4 decimal places and all the rest to 2 decimal places so if theres maybe a more direct way to do that, i'd appreciate the suggestion.
Thanks so much!
Edit: So ideally - i'd like to return this dataframe with any column that contins RB or H rounded to 4 decimal places and everything else rounded to 2.
Upvotes: 1
Views: 96
Reputation: 150735
How about:
cols = df.columns[df.columns.str.contains('RB|H')]
Upvotes: 3
Reputation: 3048
Your current code checks whether 'RB'
is true (existent) and hence returns all columns. Try:
four_dec_cols = [col for col in data_sorted if 'RB' in col or 'H' in col]
Upvotes: 0