Transposer un dataframe

lebcel -  
hugobldl Messages postés 9 Statut Membre -
Bonjour,

J'aimerais transposer uniquement une colonne d'un dataframe sous python.

Mon tableau initial est :
tab = {'ID': ['ID1','ID1','ID1','ID2','ID2'],
        'Col': [-5,0,2,0,6],
        'Val': [18,22,20,10,10]}
df = pd.DataFrame(tab, columns = ['ID', 'Col', 'Val'])
print (df)

Le tableau à obtenir est :
tab = {'ID': ['ID1','ID2'],'Col_M5': [18,0],
       'Col_M0': [22,10],
       'Col_M2': [20,0],
       'Col_M6': [0,10]}
df = pd.DataFrame(tab, columns = ['ID', 'Col_M5','Col_M0','Col_M2','Col_M6'])
print (df)


Sauriez-vous comment faire?

Merci d'avance pour votre aide !

1 réponse

  1. hugobldl Messages postés 9 Statut Membre
     
    Salut, je sais pas si c'est quelque chose comme ça que tu recherches mais je penses que la base correspond a ton besoin !
    import numpy

    tab = {'ID': ['ID1','ID1','ID1','ID2','ID2'],
    'Col': [-5,0,2,0,6],
    'Val': [18,22,20,10,10]}
    tab2 = {'ID':[]}
    tableau = []
    for listes in tab.values():
    tableau.append(listes)

    tableau = numpy.transpose(tableau)

    for listes in tableau:
    if listes[0] not in tab2['ID']:
    tab2['ID'].append(listes[0])

    colonne = 'Col_M'+str(abs(int(listes[1])))

    if colonne not in tab2:
    tab2[colonne] = []
    tab2[colonne].append(int(listes[2]))
    else:
    tab2[colonne].append(int(listes[2]))

    print(tab2)



    J'espère avoir été utile ! :)
    0