用大熊猫(python)中列名的子字符串来熔化列

问题描述 投票:1回答:4

我有数据框:

         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

而且我想将其融合到一个看起来如下的数据框:

     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          
...

...

含义,根据列名称的定界符进行融合。

最佳方法是什么?

pandas dataframe data-science melt data-munging
4个回答
0
投票

另一种方法(非常类似于@ anky_91所发布的内容。在他发布之前已经开始键入它,因此将其放在那里。)

new_df =pd.melt(df, id_vars=['subject_type','subject'], var_name='abc').sort_values(by=['subject', 'subject_type'])
new_df['cond']=new_df['abc'].apply(lambda x: (x.split('_'))[0])
new_df['value_type']=new_df.pop('abc').apply(lambda x: (x.split('_'))[-1])
new_df

输出

subject_type    subject     value   cond    value_type
0   mild              1     1          A    gd
2   mild              1     2          A    fd
4   mild              1     3          B    gd
6   mild              1     4          B    fd
1   moderate          2     11         A    gd
3   moderate          2     12         A    fd
5   moderate          2     13         B    gd
7   moderate          2     14         B    fd

0
投票

这是我使用meltmelt的方式:

series.str.split()

series.str.split()

0
投票

将索引设置为m = df.melt(['subject','subject_type']) n = m['variable'].str.split('_',expand=True).iloc[:,[0,-1]] n.columns = ['cond','value_type'] m = m.drop('variable',1).assign(**n).sort_values('subject') print(m) subject subject_type value cond value_type 0 1 mild 1 A gd 2 1 mild 2 A fd 4 1 mild 3 B gd 6 1 mild 4 B fd 1 2 moderate 11 A gd 3 2 moderate 12 A fd 5 2 moderate 13 B gd 7 2 moderate 14 B fd 。用字符串subject拆分列以创建多索引列。重命名轴为专有名称,然后单击subject_type_target_word_

stack

0
投票

用途:

reset_index
© www.soinside.com 2019 - 2024. All rights reserved.