Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert data elements in data frame via long to wide format using Panda

I have my df as below:

df

I want to convert into df2 as below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df2

I have been trying with panda, but still not able to achieve my targeted aim.

This is my sample code:

df = pd.read_excel('PathV1.xlsx')
df1 = pd.DataFrame(df, columns=['source'])
df1[['target']] = pd.DataFrame(df1['source'].str.split(':').tolist())
df1['index'] = df1.index// 3
df2 = df1[['source', 'target', 'index']].pivot(columns='source', values='target', index='index')

Appreciate any suggestions from anyone.

Many Thanks

>Solution :

First extract the values from your DataFrame that you want to transform:
data = df2.loc[:, ["source", "target"]]

Then flatten these into a single array:
data = data.values.flatten()

Now assemble them into a new DataFrame:
new_df = pd.DataFrame(data).T

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading