pandas 如何进一步将水平值融合为垂直值?

14ifxucb  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(109)

我有一个 Dataframe ,它有水平标识符(yes和no)和值,我想把它融化成垂直值,然后把它转化成每个yes。

option        Region                       Store Name       option1 option2   option3 option4    profit
0            Region 1                           Store 1        Y       Y          N        N     48.1575
1            Region 1                           Store 2        N       Y          N        Y     74.7667
2            Region 1                           Store 3        N       Y          N        Y     102.35
3            Region 2                           Store 4        N       Y          N        Y     114.59
4            Region 2                           Store 5        N       Y          N        Y     99.705
5            Region 2                           Store 6        N       Y          N        Y     105.07

需要得到的答案是:

option        Region                       Store Name       options    profit
0            Region 1                           Store 1     option1     48.1575
1            Region 1                           Store 1     option2     48.1575
2            Region 1                           Store 2     option2     74.7667
3            Region 1                           Store 2     option4     74.7667

实际上,我需要拆分客户选项表,将相同的利润分配给选择“是”的所有选项,并将选择“否”的所有选项丢弃。
到目前为止,我使用的函数是:
e1 = pd.melt(sales_dist_e, id_vars=['Area', 'Store Name'], var_name='option').set_index(['Area', 'Store Name', 'optionx']).squeeze().unstack().reset_index(),它主要是从this previous related question派生而来的,但是我似乎不能使它与我当前的示例一起工作。

4sup72z8

4sup72z81#

IIUC,这有用吗?

df.melt('option Region Store Name profit'.split(), var_name='options')\
  .query("value=='Y'")

输出量:

option  Region  Store  Name    profit  options value
0   Region       1  Store     1   48.1575  option1     Y
6   Region       1  Store     1   48.1575  option2     Y
7   Region       1  Store     2   74.7667  option2     Y
8   Region       1  Store     3  102.3500  option2     Y
9   Region       2  Store     4  114.5900  option2     Y
10  Region       2  Store     5   99.7050  option2     Y
11  Region       2  Store     6  105.0700  option2     Y
19  Region       1  Store     2   74.7667  option4     Y
20  Region       1  Store     3  102.3500  option4     Y
21  Region       2  Store     4  114.5900  option4     Y
22  Region       2  Store     5   99.7050  option4     Y
23  Region       2  Store     6  105.0700  option4     Y

相关问题