【问题标题】:pandas transform 1st mutliindex to rowindex and 2nd multiindex to columnindex熊猫将第一个多索引转换为行索引,将第二个多索引转换为列索引
【发布时间】:2021-08-28 03:33:11
【问题描述】:

所以我有以下代码将给定数据帧的组转换为列并计算每个组的大小。这将创建一个具有一列和两个值的 Multiindex 的 DataFrame。然后我将结果转换为将第二个索引作为 columnindex 并将第一个索引作为 rowindex。

import pandas as pd
from random import choice

products=['car', 'pen', 'kitchen', 'bed']
df=pd.DataFrame([{'product': choice(products), 'Changing': choice([True, False])} for _ in range(10000)])

df_grp=df.groupby(['product', 'Changing']).size().to_frame()
print(df_grp)
print('-'*50)

d=[]
for i in df_grp.reset_index()['product'].unique():
    d.append({'product':i, 'not changing': df_grp.loc[(i,False)][0], 'changing': df_grp.loc[(i,True)][0]})
print(pd.DataFrame(d).set_index('product'))

这会产生以下输出

                     0
product Changing      
bed     False     1253
        True      1269
car     False     1244
        True      1275
kitchen False     1236
        True      1271
pen     False     1206
        True      1246
--------------------------------------------------
         not changing  changing
product                        
bed              1253      1269
car              1244      1275
kitchen          1236      1271
pen              1206      1246

这正是我想要实现的。但是,我的方法似乎有点复杂。有没有更优雅的方法来做到这一点?也许使用 da 内置的 pandas 函数或 lambda 函数?此外,我的方法不能很好地概括,因为我总是假设第二个索引是布尔值。

【问题讨论】:

    标签: python pandas pandas-groupby multi-index


    【解决方案1】:

    通过unstack()尝试:

    df_grp=df.groupby(['product', 'Changing']).size().unstack()
    

    终于使用columns属性:

    df_grp.columns=[f'{"not "*col}{df_grp.columns.name}' for col in df_grp][::-1]
    #as suggested by @Cyttorak #rename column without hard coding
    #OR
    df_grp.columns=['not changing','changing'] #you have to manually write the names
    

    df_grp的输出:

              not changing  changing
    product         
    bed         1210        1226
    car         1220        1272
    kitchen     1238        1277
    pen         1267        1290
    

    【讨论】:

    • 我删除了我的。您可以添加(如果需要)可以在不使用硬封装的情况下重命名列:df_grp.columns = [f'{"not "*col}{df_grp.columns.name}' for col in df_grp]
    • 好吧,考虑到它几乎是一样的,我不介意你添加这部分。一个全面的答案比两个几乎相似的答案要好。
    猜你喜欢
    • 2014-02-04
    • 2021-12-17
    • 2019-03-26
    • 2018-11-24
    • 2021-12-08
    • 2017-10-23
    • 2022-12-04
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多