简体   繁体   English

PANDAS:将2行df转换为单行多级列df

[英]PANDAS: Convert 2 row df to single row multilevel column df

I have been searching for an answer to my question for a while, and have not been able to find anything that produces my desired result. 一段时间以来,我一直在寻找问题的答案,却找不到任何可以产生所需结果的东西。

The problem is this: I have a dataframe with two rows that I want to merge into a single row dataframe that has multi-level columns. 问题是这样的:我有一个包含两行的数据框,我想将其合并成具有多级列的单行数据框。 Using my example below (which I drafted in excel to better visualize my desired output), I want the new DF to have a multicolumn index with the first level being based on the original columns AC, then add a new column sub level based on the values from the original 'Name' column. 使用下面的示例(我在excel中起草的示例可以更好地可视化所需的输出),我希望新的DF具有多列索引,其第一级基于原始列AC,然后基于该列添加一个新的列子级。原始“名称”列中的值。 It is quite possible i'm incorrectly using existing functions. 我很有可能不正确地使用现有功能。 If you could provide me with your simplest way of altering the dataframe, I would greatly appreciate it! 如果您能为我提供最简单的更改数据框的方法,我将不胜感激!

Code to construct current df: 构造当前df的代码:

import pandas as pd
df = pd.DataFrame([['Alex',1,2,3],['Bob',4,5,6]],columns='Name A B 
C'.split())

Image of current df with desired output: 具有所需输出的当前df图像:

在此处输入图片说明

Using set_index + unstack 使用set_index + unstack

df.set_index('Name').unstack().to_frame().T
Out[198]: 
        A        B        C    
Name Alex Bob Alex Bob Alex Bob
0       1   4    2   5    3   6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM