У меня есть фрейм данных в python pandas. Я вытягиваю столбцы на основе приведенного ниже условия.
spike_cols = [col for col in nodes.columns if 'Num' in col]
print(spike_cols)
Но я ищу несколько подстрок, чтобы проверить столбцы, если они существуют. Я хочу вытащить все столбцы, которые соответствуют любой из подстрок.
spike_cols = [col for col in nodes.columns if ('Num'|'Lice') in col]
print(spike_cols)
Но я получаю ошибку ниже
: unsupported operand type(s) for |: 'str' and 'str'






попробуй это:
spike_cols = [col for col in nodes.columns if ('Num' in col or 'Lice' in col)]
Вы можете использовать DataFrame.filter для этого в сочетании с аргументом regex:
# Create example dataframe
df = pd.DataFrame({'HelloNum': [1,2],
'World':[3,4],
'This':[5,6],
'ExampleLice':[7,8]})
print(df)
HelloNum World This ExampleLice
0 1 3 5 7
1 2 4 6 8
Подать заявку DataFrame.filter
print(df.filter(regex='Num|Lice'))
HelloNum ExampleLice
0 1 7
1 2 8
Получить имена столбцов в списке
df.filter(regex='Num|Lice').columns.tolist()
['HelloNum', 'ExampleLice']