给定一个示例数据框,其中一行如下:
brand_1 gen_1 both_1 brand_2 gen_2 both_2 brand_3 gen_3 both_3
6133 5636 5446 0 3239 0 6032 5870 5484
转置或变换在我尝试对该数据进行以下重塑时不起作用:
Type Brand Gen Both
1 6133 5636 5446
2 0 3239 0
3 6032 5870 5484
我已经尝试了转换和转置以及iloc上的列块,但没有结果以这种方式重塑数据。因此,我的问题在这里。
让我们试试wide_to_long
out = pd.wide_to_long(df.reset_index(),['brand','gen','both'],i=['index'],j='Type',sep='_').reset_index()
Out[135]:
index Type both_susp_2 brand gen both
0 0 1 0 6133 5636 5446.0
1 0 2 0 0 3239 NaN
2 0 3 0 6032 5870 5484.0
你也可以使用pyjanitor中的pivot_longer函数;目前,您必须从github安装最新的开发版本:
# install latest dev version
# pip install git+https://github.com/ericmjl/pyjanitor.git
import janitor
df.pivot_longer(index = None,
names_to = ('.value', 'Type'),
names_sep = '_')
Type brand gen both
0 1 6133 5636 5446
1 2 0 3239 0
2 3 6032 5870 5484
.value
为指示剂;列名称中与.value
(brand, gen, both)对齐的部分保留为列名称,而与Type
对齐的部分成为新列Type
中的值。