【问题标题】:Pandas: How do I set index on the columns of an existing DataFrame?Pandas:如何在现有 DataFrame 的列上设置索引?
【发布时间】:2021-10-02 00:41:08
【问题描述】:

我对熊猫很陌生。 基本上,我在 10 个 dfs 中有 10 个不同公司的不同类型的数据。例如总资产、资产管理规模等
对于每种类型的数据,可能有高或低的重要性:H 或 L。
对于每种类型的数据,可能有 3 个类别:Cat1、Cat2、Cat3。

对于 H 重要性,我需要按 3 个类别分析数据。 L 重要性也一样。

我正在考虑在合并 10 个 dfs 后为每列数据添加一个多索引。这可能吗?

当前状态


**df_1**

      |Total Assets|
Firm 1| 100        |
Firm 2| 200        |
Firm 3| 300        |

**df_2**

      |AUMS    |
Firm 1| 300    |
Firm 2| 3400   |
Firm 3| 800    |
Firm 4| 800    |

and so on until df_10. Also the firms for all the df could differ.


期望的输出

**Merged_df**

Importance| L         | H    |
Category | Cat1       | Cat2 |
         |Total Assets| AUMs |
Firm 1   | 100        | 300  |
Firm 2   | 200        | 3400 |
Firm 3   | 300        | 800  |
Firm 4   | NaN        | 800  |


接下来,我需要按“重要性”和“类别”进行分组。欢迎使用除多索引之外的任何其他解决方案。谢谢!

【问题讨论】:

    标签: python pandas pandas-groupby multi-index


    【解决方案1】:

    我们可以使用MultiIndex 键在axis=1concat

    dfs = [df1, df2]
    merged_df = pd.concat(
        dfs, axis=1,
        keys=pd.MultiIndex.from_arrays([
            ['L', 'H'],       # Top Level Keys
            ['Cat1', 'Cat2']  # Second Level Keys
        ], names=['Importance', 'Category'])
    )
    

    merged_df:

    Importance            L     H
    Category           Cat1  Cat2
               Total Assets  AUMS
    Firm 1            100.0   300
    Firm 2            200.0  3400
    Firm 3            300.0   800
    Firm 4              NaN   800
    

    CategoricalDtype可用于建立排序:

    dfs = [df1, df2]
    # Specify Categorical Types
    # These lists should contain _only_ the unique categories
    # in the desired order
    importance_type = pd.CategoricalDtype(categories=['H', 'L'], ordered=True)
    category_type = pd.CategoricalDtype(categories=['Cat1', 'Cat2'], ordered=True)
    
    
    # Keys should contain the _complete_ list of _all_ columns
    merged_df = pd.concat(
        dfs, axis=1,
        keys=pd.MultiIndex.from_arrays([
            pd.Series(['L', 'H'],            # Top Level Keys
                      dtype=importance_type),
            pd.Series(['Cat1', 'Cat2'],      # Second Level Keys
                      dtype=category_type)
        ], names=['Importance', 'Category'])
    )
    

    然后可以使用sort_index,它将按预期工作。 HL 之前,等等

    # Sorting Now Works As Expected
    merged_df = merged_df.sort_index(level=[0, 1], axis=1)
    

    merged_df:

    Importance     H            L
    Category    Cat2         Cat1
                AUMS Total Assets
    Firm 1       300        100.0
    Firm 2      3400        200.0
    Firm 3       800        300.0
    Firm 4       800          NaN
    

    数据帧:

    import pandas as pd
    
    df1 = pd.DataFrame({
        'Total Assets': {'Firm 1': 100, 'Firm 2': 200, 'Firm 3': 300}
    })
    
    df2 = pd.DataFrame({
        'AUMS': {'Firm 1': 300, 'Firm 2': 3400, 'Firm 3': 800, 'Firm 4': 800}
    })
    

    【讨论】:

    • 感谢您的回复! 1)有没有办法在像df_1这样的单个df上创建多索引? 2) 如何通过列的重新排序来呈现 merge_df?我想要所有的重要性:首先是 H,然后是 CAT1、CAT2、CAT3。最后的重要性:L. 谢谢!
    • 因此,对于 (2),我添加了一个关于为自定义排序指定分类类型的代码块。例如,使H 出现在L 之前。对于 (1),MultiIndex / advanced indexing 中有很多示例。但是像 -> df1.columns = pd.MultiIndex.from_arrays([['L'], ['Cat1'], df1.columns]).
    • 感谢您的意见!我正在使用 pandas 0.20.1 并且我得到错误 no attribute CategoricalDtype。那么如何使用我的排序类别重新排序列?此外,我将顶级和二级键作为列表传递。例如 impt=['L', 'H']
    • Custom sorting in pandas dataframe 中有很多选项,很多适用于 0.20。您可能不得不改用分类。地图也可以工作。
    猜你喜欢
    • 2018-08-02
    • 2016-10-24
    • 2020-08-22
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2021-03-04
    相关资源
    最近更新 更多