Transposer un dataframe
lebcel
-
hugobldl Messages postés 9 Date d'inscription Statut Membre Dernière intervention -
hugobldl Messages postés 9 Date d'inscription Statut Membre Dernière intervention -
Bonjour,
J'aimerais transposer uniquement une colonne d'un dataframe sous python.
Mon tableau initial est :
Le tableau à obtenir est :
Sauriez-vous comment faire?
Merci d'avance pour votre aide !
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 !
A voir également:
- Transposer un dataframe
- Excel transposer avec liaison - Forum Excel
- Excel transposer une colonne en plusieurs lignes - Forum Excel
- Excel - Formule TRANSPOSE - Forum Excel
- Transposer un texte dans plusieurs lignes Excel - Forum Excel
- Transposer un bash en une ligne d'instruction sur Terminal - Forum MacOS
1 réponse
Salut, je sais pas si c'est quelque chose comme ça que tu recherches mais je penses que la base correspond a ton besoin !
J'espère avoir été utile ! :)
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 ! :)