簡體   English   中英

Pandas Dataframe,如何在 Python 中將列組合在一起

[英]Pandas Dataframe, how to group columns together in Python

我有一個熊貓數據框,我想對一些列進行分組以構建更高級別的列:

例子:我有

Index       A       B       C       D
    1    0.25     0.3    0.25    0.66
    2    0.25     0.3    0.25    0.66
    3    0.25     0.3    0.25    0.66

而且我要

    Index              AB        ||           CD
    Subindex       A   |      B  ||      C    |      D 
    1            0.25  |    0.3  ||   0.25    |    0.66
    2            0.25  |    0.3  ||   0.25    |    0.66
    3            0.25  |    0.3  ||   0.25    |    0.66

感謝您的幫助...

創建一個字典來定義你的映射並使用pd.MultiIndex.from_tuples 如果需要,您還可以指定names=['level_0', 'level_1']來添加名稱。

import pandas as pd

d = {'A': 'AB', 'B': 'AB', 'C': 'CD', 'D': 'CD'}
df.columns = pd.MultiIndex.from_tuples([*zip(map(d.get, df), df)])
# Equivalently
# df.columns = pd.MultiIndex.from_tuples([(d[col], col) for col in df.columns])

輸出:

         AB         CD      
          A    B     C     D
Index                       
1      0.25  0.3  0.25  0.66
2      0.25  0.3  0.25  0.66
3      0.25  0.3  0.25  0.66

groupby / concat hack

m = {'A': 'AB', 'B': 'AB', 'C': 'CD', 'D': 'CD'}
pd.concat(dict((*df.groupby(m, 1),)), axis=1)

         AB         CD      
          A    B     C     D
Index                       
1      0.25  0.3  0.25  0.66
2      0.25  0.3  0.25  0.66
3      0.25  0.3  0.25  0.66

請注意,使用此方法可以選擇原始 DataFrame 中列的任意子集,而替代答案似乎需要父 DataFrame 中所有值的有效字典映射

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM