Unmelt dataframe Pandas с несколькими строками с одинаковым идентификатором (несколько измерений)Python

Программы на Python
Гость
Unmelt dataframe Pandas с несколькими строками с одинаковым идентификатором (несколько измерений)

Сообщение Гость »


У меня есть объединенный фрейм данных, который содержит несколько значений для одних и тех же переменных идентификатора.

Код: Выделить всё

import pandas as pd

df = pd.DataFrame({'ID': ['A', 'A', 'B', 'B'], 'Val': [1,2,3,4]})

ID  Val
0  A    1
1  A    2
2  B    3
3  B    4
Using pivot results in an error because of repeated ID values:

Код: Выделить всё

df_unmelted=df.pivot(index="ID", values="Val", columns="ID")
ValueError: The name ID occurs multiple times, use a level number
I can manually add a repeat number in this small example to demonstrate the intended outcome but this does not work for the actual output with thousands of measurements and varying number of measurements per ID.

Код: Выделить всё

df["Repeat"] = [1,2,1,2]

ID  Val  Repeat
0  A    1       1
1  A    2       2
2  B    3       1
3  B    4       2

df_unmelted = df.pivot(index="ID", values="Val", columns="Repeat")

Repeat  1  2
ID
A       1  2
B       3  4
Is there a way to have pandas automatically number each recurrence when there are multiple values for the same ID?


Источник: https://stackoverflow.com/questions/781 ... measuremen

Вернуться в «Python»