我有一张这样的桌子

device_type version pool    testMean    testP50 testP90 testP99 testStd  WidgetMean WidgetP50   WidgetP90   WidgetP99   WidgetStd
PNB0Q7      8108162 123     124         136     140.8   141.88  21.35    2.2            0           6.4         9.64        3.92

我想让它变成这样:

device_type version pool   Name  Mean P50 P90   P99    Std
PNB0Q7      8108162 123    test  123  136 140.8 142.88 21.35
PNB0Q7      8108162 123   Widget 2.2   0  6.4   9.64  3.92

我try 使用melt,但得到:

df.melt(id_vars=["device_type", "version", "pool"], var_name="Name", value_name="Value")
device_type  version     pool  Name        Value
PNB0Q7       8108162     test  testMean     124.00
PNB0Q7       8108162     test  testP50      136.00
PNB0Q7       8108162     test  testP90      140.80
PNB0Q7       8108162     test  testP99      141.88
PNB0Q7       8108162     test  testStd      21.35

有没有关于如何达成预期解决方案的 idea

推荐答案

您可以先使用pd.wide_to_long和一点列命名清理,然后reshape 形状:

df = df.rename(columns={'Std':'testStd',
                        'TestP90':'testP90',
                        'TestP99':'testP99', 
                        'TestP50':'testP50'})
df_out = pd.wide_to_long(df, 
                         ['test','Widget'], 
                         ['device_type', 'version', 'pool'], 
                         'Measure', '', '.+' )
df_out = df_out.unstack(-1).stack(0).reset_index()
df_out

输出:

Measure device_type  version  pool level_3   Mean    P50    P90     P99    Std
0            PNB0Q7  8108162   123  Widget    2.2    0.0    6.4    9.64   3.92
1            PNB0Q7  8108162   123    test  124.0  136.0  140.8  141.88  21.35

更新上述"3级"重命名:

df = df.rename(columns={'Std':'testStd',
                        'TestP90':'testP90',
                        'TestP99':'testP99', 
                        'TestP50':'testP50'})
df_out = pd.wide_to_long(df, 
                         ['test','Widget'], 
                         ['device_type', 'version', 'pool'], 
                         'Measure', '', '.+' )\
            .rename_axis('Instrument', axis=1) #add this line to rename column header axis
df_out = df_out.unstack(-1).stack(0).reset_index()
df_out

输出:

Measure device_type  version  pool Instrument   Mean    P50    P90     P99    Std
0            PNB0Q7  8108162   123     Widget    2.2    0.0    6.4    9.64   3.92
1            PNB0Q7  8108162   123       test  124.0  136.0  140.8  141.88  21.35

Python-3.x相关问答推荐

网站抓取:当我使用Chrome DevTools中的网络选项卡时,找不到正确的URL来提供我想要的数据

小部件padx和包方法ipadx有什么不同?

如何检索与美汤相似的标签中的文本?

PYSMB中的进度条

tkinter/python3.9 中的 Entry 子类和用户输入重复的问题

Django中自动设置/更新字段

如何沿单列获取嵌套列表中的唯一值?

Einsum 对于张量乘法很慢

考虑到Pandas 系列中的不同索引,如何正确估计两列的百分比变化? Python相关

判断 gekko 中的表达式

是否将dict转换为一个数据帧,每个值都有重复的键?

将变量传递给 Google Cloud 函数

两个Pandas数据框中的共同列列表

如何注释一个以另一个函数作为参数的函数?

python total_ordering:为什么使用 __lt__ 和 __eq__ 而不是 __le__?

如何在 Selenium 和 Python 中使用类型查找元素

使用 python2 和 python3 创建一个 virtualenv

用于 unicode 大写单词的 Python 正则表达式

带有自定义标头的 urllib.urlretrieve

在 Meta 中创建具有动态模型的通用序列化程序