python - 堆积柱

标签 python pandas dataframe

我有一个看起来像的 df

<表类=“s-表”> <标题> L.1 L.2 G.1 G.2 <正文> 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16

这只是一个任意的例子,但我的 df 的结构是完全相同的。 4 个列标题及其下方的数字。我想以看起来像这样的方式堆叠我的列

<表类=“s-表”> <标题> L G <正文> 1 9 2 10 3 11 4 12 5 13 6 14 7 15 8 16

如果有人可以帮助我解决这个问题,那就太好了,因为我真的很难做到这一点。

最佳答案

使用wide_to_long删除 DataFrame.reset_index 中的 MultiIndexdrop=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_indexMultiIndex 进行排序,最后还删除 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/

相关文章:

Python Pandas : split and change the date format(one with eg:(aug 2018 - nov 2018)) and other with only one?

python - 如何使用 pandas 从 CSV 文件读取字节数组?

python - 如何防止Pandas出现 "None of [MultiIndex...] are in the [columns]"?

python - Taipy:没有显示图表,可能是由于行中的 "Invalid tag name ' 文本”

python - 从 Python 2.7 中的 args/kwargs 和函数签名填充默认缺失/参数

python - 一个预测中的目标值数量

python - 如何找到生成 Pandas SettingWithCopyWarning 的行?

python - 根据行号删除数据帧的行

python - openpyxl 字体条件格式

python - 从 Pandas 数据帧创建边缘列表