英文:
Reorganise Columns in MultiIndex Matrix Pandas
问题
我帮您翻译一下您的请求,将代码部分保持不变:
我有一个 pandas 数据框,其中每一行都有来自不同高度传感器的一些读数。我使用 df.pivot 函数将这些读数转换为矩阵,其中索引是标识符,列是不同的高度,以及在这些高度上的三个数据值。
我的矩阵看起来像这样(Data 是级别 0 的列标题,Alt 是级别 1):
Data_1. | Data_2 | Data_3. |
---|---|---|
Alt_1 - Alt_2 - Alt_3 - ... | Alt-1 - Alt_2 - Alt_3 - ... | Alt_1 - Alt_2 - Alt_3 - ... |
我希望将多级索引列重新排列,使级别 0 成为高度,级别 1 成为数据。
我尝试了各种方法来更改级别,重命名元组等,但没有找到有用的方法。
我期望表格看起来像这样:
Alt 1. | Alt_2 | Alt_3 | ... |
---|---|---|---|
Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 |
英文:
I have a pandas data frame where every row has a some readings from a sensor at different altitudes. I managed to get these readings in a matrix using the df.pivot function, where the index the identifier is, the columns the different altitude and three values of data at those altitudes.
My matrix looks like this (Data is level 0 column header, Alt is level 1)
Data_1. | Data_2 | Data_3. |
---|---|---|
Alt_1 - Alt_2 - Alt_3 - ... | Alt-1 - Alt_2 - Alt_3 - ... | Alt_1 - Alt_2 - Alt_3 - ... |
What I want is to get the multi-index columns rearranged so that the level 0 as the altitudes and the level 1 is the data.
I tried various ways of changing levels, renaming tuples etc.. but found nothing useful.
I expect the table to look like this:
Alt 1. | Alt_2 | Alt_3 | ... |
---|---|---|---|
Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 | Data_1-Data_2-Data_3 |
答案1
得分: 2
我认为这就是swaplevel发挥作用的地方。试一试:
df.swaplevel(axis=1)
示例:
df = pd.DataFrame(
{"Grade": ['A','B','C','D','E','F','G','H','I']},
index=[
['Data_1']*3 + ['Data_2']*3 + ['Data_3']*3,
['Alt_1','Alt_2','Alt_3']*3]).T
在上面的示例中,转换之前的DataFrame如下所示:
Data_1 Data_2 Data_3
Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3
Grade A B C D E F G H I
进行转换之后:
df.swaplevel(axis=1)
得到:
Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3
Data_1 Data_1 Data_1 Data_2 Data_2 Data_2 Data_3 Data_3 Data_3
Grade A B C D E F G H I
英文:
I think this is where swaplevel shines. Try with:
df.swaplevel(axis=1)
Example:
df = pd.DataFrame(
{"Grade": ['A','B','C','D','E','F','G','H','I']},
index=[
['Data_1']*3 + ['Data_2']*3 + ['Data_3']*3,
['Alt_1','Alt_2','Alt_3']*3]).T
Which looks as follows:
Data_1 Data_2 Data_3
Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3
Grade A B C D E F G H I
After the transformation:
df.swaplevel(axis=1)
We get:
Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3 Alt_1 Alt_2 Alt_3
Data_1 Data_1 Data_1 Data_2 Data_2 Data_2 Data_3 Data_3 Data_3
Grade A B C D E F G H I
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论