#python #pandas
Вопрос:
У меня есть фрейм данных следующим образом:
ab = {
'Category': ['AD', 'AG'],
'C1_count': ['agitation, care=4; anxiety=3; ataxia=1; cognitive/trek=0', 'agitation=4; anxiety,check=0; ataxia=1; cognitive=1'],
'C2_count': ['agitation=0; anxiety=1; ataxia=1; cognitive=0', 'agitation=0; anxiety=1; ataxia, bee and jee=0; cognitive=0']
}
df1 = pd.DataFrame(ab)
df1
Category C1_count C2_count
0 AD agitation, care=4; anxiety=3; ataxia=1; cognitive/trek=0 agitation=0; anxiety=1; ataxia=1; cognitive=0
1 AG agitation=4; anxiety,check=0; ataxia=1; cognitive=1 agitation=0; anxiety=1; ataxia, bee and jee=0; cognitive=0
Я хочу удалить термины в фрейме данных, которые равны 0
. Ожидаемый результат выглядит следующим образом:
Category C1_count C2_count
0 AD agitation, care=4; anxiety=3; ataxia=1 anxiety=1; ataxia=1
1 AG agitation=4; ataxia=1; cognitive=1 anxiety=1
Ответ №1:
попробуйте через applymap()
:
f=lambda x:';'.join([y for y in x.split(';') if '=0' not in y])
#Finally:
df1[['C1_count','C2_count']]=df1[['C1_count','C2_count']].applymap(f)
выход из df
:
Category C1_count C2_count
0 AD agitation, care=4; anxiety=3; ataxia=1 anxiety=1; ataxia=1
1 AG agitation=4; ataxia=1; cognitive=1 anxiety=1
Комментарии:
1. этот код работает частично. потому что он также удаляет слово, когда содержит имя слова
0
. Напримерagitation0 use=5
, также будет удален.2. @user288925 обновленный ответ…пожалуйста, посмотрите и дайте мне знать, есть ли еще такой случай 🙂
Ответ №2:
Вы можете pandas.Series.str.replace
с помощью регулярного выражения:
df1['C1_count'] = df1['C1_count'].str.replace('(; )?[^= ] =0| ?[^= ] =0;',
'', regex=True)
df1['C2_count'] = df1['C2_count'].str.replace('(; )?[^= ] =0| ?[^= ] =0;',
'', regex=True)
выход:
Category C1_count C2_count
0 AD agitation, care=4; anxiety=3; ataxia=1 anxiety=1; ataxia=1
1 AG agitation=4; ataxia=1; cognitive=1 anxiety=1
Комментарии:
1. этот код работает частично. потому что он также удаляет слово, когда содержит имя слова
0
. Напримерagitation0 use=5
, также будет удален2. Вы проверили? Я почти уверен, что это не так. Для совпадения требуется «=» прямо перед 0.