简体   繁体   English

仅转置 Pandas MultiIndex 数据帧的一层

[英]Transpose only one level of a pandas MultiIndex dataFrame

I am trying to reformat a DataFrame, turning values in a row into columns.我正在尝试重新格式化 DataFrame,将一行中的值转换为列。 I tried using melt but just got errors.我尝试使用melt,但出现错误。 Transpose seemed to get me part of the way there, but gave weird output (because the input was a grouped DataFrame I think)转置似乎让我参与了其中,但给出了奇怪的输出(因为我认为输入是分组的 DataFrame)

d = {'name':['bil','bil','bil','jim'],
     'col2': ['acct','law', 'acct2','law'],
     'col3': [1,2,3,55]
    }
df2 = pd.DataFrame(data=d)

df2.groupby(['name','col2']).agg({'col3':'first'})

OUTPUT:输出:

name    col2      col3
bil     acct        1
        acct2       3
        law         2
jim     law        55

GOAL:目标:

     acct acct2 law
bill 1     3     2
jim              55

You can use first directly.可以first直接使用。 Also, you'll need unstack with a custom fill_value :此外,您还需要使用自定义fill_value unstack

(df2.groupby(['name', 'col2'])['col3']
    .first()
    .unstack(fill_value='')
    .rename_axis(None, 1))

     acct acct2 law
name               
bil     1     3   2
jim              55

暂无
暂无

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

相关问题 按一级MultiIndex对熊猫DataFrame进行排序 - Sorting a pandas DataFrame by one level of a MultiIndex 熊猫MultiIndex更改顺序仅一级 - Pandas MultiIndex change order of one level ONLY 附加到 Multiindex pandas DataFrame 中的级别 - append to level in Multiindex pandas DataFrame 熊猫:数据帧到面板错误:NotImplementedError:仅支持2级MultiIndex - Pandas: Dataframe to Panel error: NotImplementedError: Only 2-level MultiIndex are supported python pandas multiIndex Dataframe,如何基于iloc选择一个级别 - python pandas multiIndex Dataframe, how to select one level based on iloc 为什么在具有一级索引的 MultiIndex 列的 pandas DataFrame 中的行为不同? - Why in a pandas DataFrame with a MultiIndex columns of one level indexing behaves differently? Pandas Dataframe MultiIndex将多级索引中的一个转换为另一轴,同时将另一级保留在原始轴中 - Pandas Dataframe MultiIndex transform one level of the multiindex to another axis while keeping the other level in the original axis 如何仅基于外部索引转置多级熊猫数据帧 - how to transpose multiple level pandas dataframe based only on outer index 仅使用一级索引设置多索引数据帧的值 - Setting values of multiindex dataframe using only one-level indexing 有没有办法向仅与一个级别对齐的 pandas 多索引添加新列? - Is there a way to add a new column to a pandas multiindex that only aligns with one level?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM