繁体   English   中英

交换字典键和列名

[英]Swapping dictionary keys and column names

这是我的问题的 MWE。

我有一本带有“A”、“B”、“C”、“D”键的字典。 每个字典值都是一个 dataframe,具有相同的列“1”、“2”、“3”、“4”。

我希望将数据格式更改为带有键“1”、“2”、“3”、“4”的字典。 内部包含“A”、“B”、“C”、“D”列的数据框。

字典“A”的“1”列中的数据将最终出现在字典“1”的“A”列中。

这是构造初始字典的代码:

import numpy as np
dict_num ={}
for i in range(1,5): 
    dict_num[i] = pd.DataFrame(np.random.randint(0,100,size=(5, 4)), columns=list('ABCD'))

这是转换的代码:

def convert_dictionary(dict_num): 
    col_num = list(dict_num.values())[0].columns # Extract the column names of first dictionary (columns in all df are identical)
    alpha_df = pd.DataFrame() #Create empty dataframe 
    dict_alpha = {key: alpha_df for key in col_num} #Create new dictionary with columns as keys and the empty dictionary as keys 
    for df in dict_num: #Iterate through the initial dictionary
        for column in dict_num[df]:  #Iterate through the initial columns
            dict_alpha[column].insert(len(dict_alpha[column].columns), df, dict_num[df][column])# Insert the column into the new dictionary with column and key switched 
    return dict_alpha

dict_alpha = convert_dictionary(dict_num)

第一列正确地进入 dict_alpha['A'] 中的列 '1'。 下一列应作为列 '1' 进入下一个新字典 dict_alpha['B']。 但是,我得到一个 ValueError。 我假设 output 正在复制到所有字典中,但我不知道如何。

在 function 中创建dict_alpha时,您指的是相同的空 dataframe alpha_df因此相同的 memory 空间,将其替换为

dict_alpha = {key: pd.DataFrame() for key in col_num}

并且不再需要定义alpha_df

您还可以使用concatgroupby进行操作:

dict_alpha = {key : val.droplevel(axis=1,level=1) 
              for key, val in pd.concat(dict_num, axis=1).groupby(level=1, axis=1)}

只需检查这是否是您正在寻找的解决方案。

def convert_dictionary(dict_num): 
    col_num = list(dict_num.values())[0].columns
    alpha_df = pd.DataFrame() #Create empty dataframe 
    dict_alpha = {}
    for k,v in dict_num.items(): #Iterate through the initial dictionary
        for column in v.columns:
            df=pd.DataFrame({k:v[column]})
            dict_alpha.update({column:pd.concat([dict_alpha.get(column),df],axis=1)})
    return dict_alpha

暂无
暂无

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

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