bella
bella

Reputation: 33

Scala: Convert columns into rows based on index 0 value?

I have a dataframe that contains the name of the item and then all the prices that item was sold for - I want to turn them all into separate rows.

df looks like this:

Name
orange 1.0 1.5 1.2 1.3 1.8
apple 1.5 1.4 1.3
pear 0.8 0.9 1.0 0.8

expected output:

Name Price
orange 1.0
orange 1.5
orange 1.2
orange 1.3
orange 1.8
apple 1.5
apple 1.4
apple 1.3
pear 0.8
pear 0.9
pear 1.0
pear 0.8

I have tried using pivot(), groupBy() and explode() but nothing's working :(

Upvotes: 0

Views: 30

Answers (1)

pyaj
pyaj

Reputation: 640

Try this:

pd.melt(df, id_vars='Name').sort_values(by=['Name'])

Upvotes: 0

Related Questions