I just started with python and know almost nothing about pandas.
so now I have a directed graph which look like this:
from ID | to ID |
---|---|
13 | 22 |
13 | 56 |
14 | 10 |
14 | 15 |
14 | 16 |
now I need to transform it to horizontal data format like this:
from ID | To 0 | To 1 | To 2 |
---|---|---|---|
13 | 22 | 56 | NAN |
14 | 10 | 15 | 16 |
I find something like Pandas Merge duplicate index into single index but it seems it cannot merge rows into different colums.
Will pandas use NAN to fill in the blanks during this process due to the need to add more columns?
CodePudding user response:
You can do something like this to transform your dataframe, pandas will automatically add NaN values for any number of columns you have with this solution.
df = df.groupby('from')['to'].apply(list)
## create the desired df from the lists
df = pd.DataFrame(df.tolist(),index=df.index).reset_index()
## Rename columns
df.columns = ["from ID"] [f"To {i}" for i in range(1,len(df.columns))]