Home > Net >  Reshaping a dataframe to a new Dataframe
Reshaping a dataframe to a new Dataframe

Time:09-24

enter image description here

Hi, I want to reshape the data frame to the right one. A, B, C, ... could be the name of a person.

this is my data: https://www.udrop.com/5YbK/RelationMatrix.csv

CodePudding user response:

Use DataFrame.stack with joined MultiIndex in map:

df1 = df.stack()
df1.index = df1.index.map(lambda x: f'{x[0]}{x[1]}')
df1 = df1.rename_axis('Link').reset_index(name='Value')

For better performance is possible use:

c = np.tile(df.columns, len(df))
i = np.repeat(df.index, len(df.columns))
v = np.ravel(df)

df = pd.DataFrame({'Link':c, 'b': i, 'value': v})
df['Link'] = df['Link'].str.cat(df.pop('b'))
  • Related