pandas 中的一种变换
A kind of transform in pandas
给定一个包含一行的示例数据框:
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
我已经在列块上尝试了 Transform 和 Transpose 以及 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
您也可以使用 pivot_longer function from pyjanitor; at the moment you have to install the latest development version from 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
.[= 中的值16=]
给定一个包含一行的示例数据框:
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
我已经在列块上尝试了 Transform 和 Transpose 以及 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
您也可以使用 pivot_longer function from pyjanitor; at the moment you have to install the latest development version from 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
.[= 中的值16=]