python - 将列表从大量字典转换为数据框的问题

标签 python dataframe

我用这种方式创建了一个字典:

数据如下所示:

GDS3:
ABC_1     ABC_2     BBB_1
cat        elf       123
dog        run       456
bird       burp      789

GDS4:
ABC_3     ABC_4     BCB_a
beer        yes      234
wine        no       543
gin         yes      743

GDS5:
ABC_5     ABC_6     BCD_c
lol        yea       543
lmao       NaN       446
asl        NaN       777

#create a dictionary in which all columns that start with the same 3 characters will be grouped in the same key. 
dict_2013 = {k: g for k, g in GDS3.groupby(by=lambda x: x[:3].lower(), axis=1)}

dict_2014 = {k: g for k, g in GDS4.groupby(by=lambda x: x[:3].lower(), axis=1)}

dict_2015 = {k: g for k, g in GDS5.groupby(by=lambda x: x[:3].lower(), axis=1)}

#start with year 2013:
global_dict=dict_2013

#if key in the new dictionary is in the old dictionary then 
#add the values from the new dictionary key to the old dictionary key
#else if the new dictionary key does not exist in the old dictionary then add a new key with the new values

for key,val in dict_2014.items():
    if key in global_dict:
       global_dict[key]=[global_dict[key],val]
    else:
       global_dict[key]=val

for key,val in dict_2015.items():#to add items
    if key in global_dict:
        global_dict[key]=[global_dict[key],val]
    else:
       global_dict[key]=val

这是我想要的输出(每个键的数据框)

  df_ABC:
  ABC_1     ABC_2     ABC_3   ABC_4   ABC_5
  cat        elf       beer    yes    lol
  dog        run       win     no     lmao
  bird       burp      gin     yes    asl

  df_BBB:
  BBB_1
  cat   
  dog        
  bird      

换句话说,我想将单个键转换为单个字典(对于所有键),所以我尝试了以下操作:

ABC_dataframe=pd.DataFrame(global_dict['ABC'])

当我这样做时,出现以下错误:

TypeError: Expected list, got DataFrame

这很奇怪,因为 global_dict['ABC'] 是一个列表。 (我使用类型(global_dict['ABC'])进行了检查。

我该怎么做才能纠正这个问题?我尝试展平列表,但仍有问题。

最佳答案

您的逻辑中最令人困惑的部分是将 global_dict 值设置为数据框或列表。保持对象类型一致;选择列表并在每次您希望添加值时附加到它。

Pythonic 解决方案是使用 list 对象的 collections.defaultdict:

from collections import defaultdict

global_dict = defaultdict(list, {k: [v] for k, v in dict_2013.items()})

for key,val in dict_2014.items():
    global_dict[key].append(val)

for key,val in dict_2015.items():
    global_dict[key].append(val)

然后沿axis=1使用pd.concat:

abc = pd.concat(global_dict['abc'], axis=1)

print(abc)

  ABC_1 ABC_2 ABC_3 ABC_4 ABC_5 ABC_6
0   cat   elf  beer   yes   lol   yea
1   dog   run  wine    no  lmao   NaN
2  bird  burp   gin   yes   asl   NaN

我无法解释为什么您想要的结果缺少 ABC_6

关于python - 将列表从大量字典转换为数据框的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156423/

相关文章:

python - cv2.matchTemplate 给出错误 : (-215:Assertion failed)

python - 取决于计算 groupby 对象中两个列单元格之间的差异的列

python - 在 Python 中为每一列使用相同的列表创建 Pandas DataFrame

python - 将 python 3 中的生成器与 +-operator 连接起来

python - 检测无效文件输入,Python

python - Django 查询性能过滤与外键集查找

python - 如何仅合并 Pandas 中的特定数据框列?

python - 根据大量 python 数据框的字数删除关键字

python - 将数字转换为 pandas DataFrame 中的特定字符串格式

python - 在views.py django中检索多个单选按钮和表单字段的值