gpt4 book ai didi

python - 从分类列中为分类值创建一行

转载 作者:行者123 更新时间:2023-11-28 22:29:53 25 4
gpt4 key购买 nike

这是我在 StackOverflow 上的第一个问题。我希望你能帮助解决一个困扰我一段时间的问题。我找不到合适的答案。

我的数据是这样的:

df = pd.DataFrame({'col1': {0: 1, 1: 1, 2: 1},
'col2': {0: 1, 1: 2, 2: 3},
'col3': {0: 1, 1: 2, 2: 3},
'col4': {0: 1.1, 1: 2.1, 2: 3.1},
'col5': {0: 10, 1: 12, 2: 14},
'col6': {0: 1.2, 1: 2.2, 2: 3.2},
'col7': {0: 11, 1: 13, 2: 15},
})
df.columns = ["VZ", "NZ", "L", "T_0_Rel", "T_0_Abs", "T_Akt_Rel", "T_Akt_Abs"]
df

哪些输出(没有索引列):

╔════╦════╦═══╦═════════╦═════════╦═══════════╦═══════════╗
║ VZ ║ NZ ║ L ║ T_0_Rel ║ T_0_Abs ║ T_Akt_Rel ║ T_Akt_Abs ║
╠════╬════╬═══╬═════════╬═════════╬═══════════╬═══════════╣
║ 1 ║ 1 ║ 1 ║ 1.1 ║ 10 ║ 1.2 ║ 11 ║
║ 1 ║ 1 ║ 2 ║ 2.1 ║ 12 ║ 2.2 ║ 13 ║
║ 1 ║ 1 ║ 3 ║ 3.1 ║ 14 ║ 3.2 ║ 15 ║
╚════╩════╩═══╩═════════╩═════════╩═══════════╩═══════════╝

现在我想将这个 DataFrame 扭曲成这样的东西:

╔════╦════╦═══╦═════════════╦═════╦═════╗
║ VZ ║ NZ ║ L ║ T_0 / T_Akt ║ Abs ║ Rel ║
╠════╬════╬═══╬═════════════╬═════╬═════╣
║ 1 ║ 1 ║ 1 ║ T_0 ║ 10 ║ 1.1 ║
║ 1 ║ 1 ║ 1 ║ T_Akt ║ 11 ║ 1.2 ║
║ 1 ║ 2 ║ 2 ║ T_0 ║ 12 ║ 2.1 ║
║ 1 ║ 2 ║ 2 ║ T_Akt ║ 13 ║ 2.2 ║
║ 1 ║ 3 ║ 3 ║ T_0 ║ 14 ║ 3.1 ║
║ 1 ║ 3 ║ 3 ║ T_Akt ║ 15 ║ 3.2 ║
╚════╩════╩═══╩═════════════╩═════╩═════╝

基本上,我希望每个 T_O 和 T_Akt 值都占一行,而 Abs 和 Rel 值可以保留在一行中。

我认为这应该可以通过 .stack().melt() 实现,但我可以弄清楚如何去做。

我的意图是在我的 DataFrame 中有一个分类值,以便在 seaborn.boxplot.violinplot 中使用 hue 参数强>功能。我无法弄清楚如何使用具有多个列的色调参数而不是分类值。(也许我在这里错了,还有更简单的方法......)

非常感谢。

最佳答案

既然你在概念上有一个层次化的列索引,我会这样做然后使用 stack

df = pandas.DataFrame({
'VZ': {0: 1, 1: 1, 2: 1},
'NZ': {0: 1, 1: 2, 2: 3},
'L': {0: 1, 1: 2, 2: 3},
'T_0_Rel': {0: 1.1, 1: 2.1, 2: 3.1},
'T_0_Abs': {0: 10, 1: 12, 2: 14},
'T_Akt_Rel': {0: 1.2, 1: 2.2, 2: 3.2},
'T_Akt_Abs': {0: 11, 1: 13, 2: 15},
})

print(
df.set_index(['VZ', 'NZ', 'L']) # row labels
.rename(columns=lambda c: tuple(c.rsplit('_', 1))) # create the multi-cols
.stack(level=0) # unpivot
.reset_index() # move the row labels back into normal columns
)

我明白了:

   VZ  NZ  L level_3  Abs  Rel
0 1 1 1 T_0 10 1.1
1 1 1 1 T_Akt 11 1.2
2 1 2 2 T_0 12 2.1
3 1 2 2 T_Akt 13 2.2
4 1 3 3 T_0 14 3.1
5 1 3 3 T_Akt 15 3.2

关于python - 从分类列中为分类值创建一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com