Reconstrua o Dataframe do pandas com declarações if
Como já perguntei em outra pergunta com o título "Reconstruir o Dataframe do pandas", ainda tenho algumas perguntas sobre como continuar com ainda mais colunas.
Situação: Eu tenho um Dataframe com 4 colunas, os valores dentro das colunas são bastante aleatórios. Como este exemplo:
df = pd.DataFrame({'col1': ['id 1', 'id 2', 'test 3', 'test 4'],
'col2': ['test 1', 'test 2',
'ne 5261', 'id 4'],
'col3': ['Number 12344', 'Number 21612','id 3','Number 1131'],
'col4':['ne 315','Number 1264777','ne 1415','ne 52']})
Meu objetivo é ter um Dataframe em que cada Col tenha apenas os valores começando com a mesma substring como este exemplo:
O que já funcionou para 3 colunas é o seguinte código (dos créditos da última pergunta para: @AndrejKesely):
def key_fn(x):
if 'id' in x:
return 0
if 'test' in x:
return 1
if 'Number' in x:
return 2
return 3
df = pd.DataFrame([sorted(l, key=key_fn) for l in df.values], columns=df.columns)
imprimir (df)
Como agora tenho 4 colunas, adicionei outra instrução if à função, da seguinte maneira:
def key_fn(x):
if 'id' in x:
return 0
if 'test' in x:
return 1
if 'Number' in x:
return 2
if 'ne' in x:
return 3
return 4
df = pd.DataFrame([sorted(l, key=key_fn) for l in df.values], columns=df.columns)
Isso me dá o seguinte resultado:
Este é um pequeno exemplo, quando eu entendo como funciona, preciso aplicá-lo a um total de 17 colunas. Agradeço antecipadamente por sua ajuda!
Respostas
df = pd.DataFrame({'col1': ['id 1', 'id 2', 'test 3', 'test 4'],
'col2': ['test 1', 'test 2',
'ne 5261', 'id 4'],
'col3': ['Number 12344', 'Number 21612','id 3','Number 1131'],
'col4':['ne 315','Number 1264777','ne 1415','ne 52']})
def key_fn(x):
if 'id' in x:
return 0
if 'test' in x:
return 1
if 'Number' in x:
return 2
if 'ne' in x:
return 3
return 4
out_df = pd.DataFrame(np.array(sorted(np.ravel(df.values), key=key_fn)).reshape(df.shape), columns=df.columns).T
print(out_df)
Impressões:
col1 col2 col3 col4
0 id 1 test 1 Number 12344 ne 315
1 id 2 test 2 Number 21612 ne 5261
2 id 3 test 3 Number 1264777 ne 1415
3 id 4 test 4 Number 1131 ne 52