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.
怎么样:
cols = df.columns[df.columns.str.contains('RB|H')]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.