0

I have dataframe:

         subject           A_target_word_gd  A_target_word_fd B_target_word_gd  B_target_word_fd  subject_type 
           1                      1             2                3                    4             mild 
           2                      11            12               13                   14             moderate

And I want to melt it to a dataframe that will look:

     cond    subject    subject_type     value_type   value
      A         1        mild             gd           1           
      A         1        mild             fg           2           
      B         1        mild             gd           3            
      B         1        mild             fg           4  
      A         2        moderate         gd           11           
      A         2        moderate         fg           12           
      B         2        moderate         gd           13            
      B         2        moderate         fg           14          
...

...

Meaning, to melt based on the delimiter.

What is the best way to do that?

Cranjis
  • 1,590
  • 8
  • 31
  • 64
  • 2
    `df[['cond','level','word','value_type']] = df['cond'].str.split('_',expand=True)` ? then you can drop the `word` column – anky Dec 29 '19 at 13:22
  • 1
    I do not see any application of melt here. You can just generate new columns in different ways. `df['cond_new'] = df['cond'].apply(lambda x: x.split()[0] if x is not None else x)` and do the same to get the other column or can follow anky_91 – DataPsycho Dec 29 '19 at 13:32
  • @DataPsycho I'm sorry I was confused and didn't write the original df good, please see my edit – Cranjis Dec 29 '19 at 14:32
  • 1
    Does this answer your question? [melt column by substring of the columns name in pandas (python)](https://stackoverflow.com/questions/59550804/melt-column-by-substring-of-the-columns-name-in-pandas-python) – ralf htp Jan 04 '20 at 06:10

1 Answers1

0

You can use str.split() to melt on the delimiter, this is explained in melt data frame and split values for R and in Python melt dataframe based on values of comma-separated character vector column and Python melt dataframe based on values of comma-separated character vector column for python

ralf htp
  • 9,149
  • 4
  • 22
  • 34