我有一个看起来像的 df
这只是一个任意的例子,但我的 df 的结构是完全相同的。 4 个列标题及其下方的数字。我想以看起来像这样的方式堆叠我的列
如果有人可以帮助我解决这个问题,那就太好了,因为我真的很难做到这一点。
最佳答案
使用wide_to_long
删除 DataFrame.reset_index
中的 MultiIndex
与drop=True
:
df = (pd.wide_to_long(df.reset_index(), stubnames=['L','G'], i='index', j='tmp', sep='.')
.reset_index(drop=True))
print (df)
L G
0 1 9
1 2 10
2 3 11
3 4 12
4 5 13
5 6 14
6 7 15
7 8 16
或按str.split
分割列与 DataFrame.stack
并按 DataFrame.sort_index
对 MultiIndex
进行排序,最后还删除 MultiIndex
:
df.columns = df.columns.str.split('.', expand=True)
df = df.stack().sort_index(level=[1,0]).reset_index(drop=True)
print (df)
G L
0 9 1
1 10 2
2 11 3
3 12 4
4 13 5
5 14 6
6 15 7
7 16 8
关于python - 堆积柱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67528872/