Python 为分类列中的分类值创建行
这是我在StackOverflow的第一个问题。我希望你能帮我解决一个困扰我一段时间的问题。我找不到合适的答案 我的数据如下所示:Python 为分类列中的分类值创建行,python,pandas,seaborn,Python,Pandas,Seaborn,这是我在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},
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 / 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 ║
╚════╩════╩═══╩═════════════╩═════╩═════╝
哪些输出(无索引列):
现在,我想将此数据帧扭曲成如下内容:
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 / 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()实现,但我可以想出方法
这一切背后的意图是在我的数据帧中有一个分类值,以便在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