Вот что выдает мой код:
Код: Выделить всё
aac(6')=HMM aac(6')-I=COMPLETE aac(6')-Ib-cr5=COMPLETE aac(6')-Ie/aph(2'')-Ia=COMPLETE...
the_meat ; ; ;1687 0 0 0 0 0 ...
the_meat ;chicken ; ;205 0 0 0 0 0 ...
the_meat ;chicken ;cajan chicken salad ;1 0 0 0 0 0 ...
Я хотел, чтобы это выглядело так
Тип
Подтип
Подподтип
N
AMR1
AMR2
...
Мясо
1687
0
0
...
Мясо
Курица
205
0
0
...
Мясо
Курица
салат с курицей по-каянски
1
0
0
...
Как превратить индекс в столбец? Можно ли это сделать на этапе join()?
Вот мой код. Мне жаль, что это может вызвать отвращение у опытных программистов.
Код: Выделить всё
x_axel=[]
amrS = uag.set_index('AMRs')
for i in x: # x is list food types: meat, fish, vegetables...
y=ft[i].dropna().tolist() #variable is the header.
pattern = '|'.join(map(re.escape, y))
typeF = df[df['Isolation source'].str.contains(pattern, case=False, na=False)]
df_type= pd.melt(typeF, id_vars=['Isolation source'], value_name=i)[i].value_counts().reset_index()
df_type.columns = ['AMRs' ,f'{i} ; - ; - ;{typeF.shape[0]} ']
x_axel.append(df_type)
for j in y: #subtype
subtypeF = df[df['Isolation source'].str.contains(j, case=False, na=False)] #replase pattern with j
df_subtype= pd.melt(subtypeF, id_vars=['Isolation source'], value_name=i)[i].value_counts().reset_index()
df_subtype.columns = ['AMRs',f'{i} ;{j}; - ;{subtypeF.shape[0]} ']
x_axel.append(df_subtype)
subsubTL=list(set(subtypeF['Isolation source'].to_list()))
for k in subsubTL: #individual foods
subsubtypeF = df[df['Isolation source'].str.contains(f'{k}')] #EXTRACT, not contains
df_subsubtype = pd.melt(subsubtypeF, id_vars=['Isolation source'], value_name=i)[i].value_counts().reset_index()
df_subsubtype.columns = ['AMRs', f'{i} ;{j};{k} ;{subsubtypeF.shape[0]} ']
x_axel.append(df_subsubtype)
others = [d.set_index('AMRs') for i, d in enumerate(x_axel)]
final_df = amrS.join(others, how='left').fillna(0).astype(int).transpose()
final_df[['Type', 'Subtype', 'Sub-subtype', 'N']] = final_df.[0].apply(lambda x: pd.Series(str(x).split(";")
Подробнее здесь: https://stackoverflow.com/questions/799 ... and-transp
Мобильная версия