【问题标题】:Issues converting lists from massive dictionary to dataframe将列表从海量字典转换为数据框的问题
【发布时间】:2018-09-03 21:38:45
【问题描述】:

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

数据如下:

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'] 是一个列表。 (我使用 type(global_dict['ABC']) 进行了检查。

我能做些什么来纠正这个问题?我尝试扁平化列表,但我仍然遇到问题。

【问题讨论】:

  • pd.DataFrame 需要一个列表列表或字典列表。你所拥有的是一个嵌套的数据框列表。如果不清楚,请尝试print(global_dict['abc'])(不确定alc 来自哪里)。
  • 谢谢@jpp。然后,我将如何将嵌套的数据框列表变成一个数据框。我已经更正了您指出的“alc”错字。谢谢。
  • 我不知道,因为你没有显示你想要的输出in your question。
  • @jpp,我现在已经为我的问题包含了所需的输出。谢谢!
  • GDS3、GDS4 和 GDS5 数据帧最初是?是否需要将它们转换为字典?

标签: python dataframe


【解决方案1】:

如果 GDS3、GDS4 和 GSD5 已经是数据帧,您可以使用 pd.concat 和 groupby 来实现:

tdf = pd.concat([GDS3, GDS4, GDS5], axis=1)

g = tdf.groupby(tdf.columns.str[:3], axis=1)

# Now, let's create a dictionary of dataframes grouped 
# by the first three letters of each column.

df_list = {}
for n, i in g:
    df_list[n] = i


print(df_list['ABC'])
print(df_list['BBB'])

或者按照@jpp 的建议使用:

dict_dfs = dict(tuple(g))

print(dict_dfs['ABC'])
print(dict_dfs['BBB'])

输出:

  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
   BBB_1
0    123
1    456
2    789

【讨论】:

  • 很好,绝对是比我更好的解决方案。你不能做类似dict(tuple(g)) 的事情,而不是手动的for 循环吗?
  • @jpp 谢谢。感谢您的评论。
  • @jpp 是的,酷。我也喜欢。
  • 感谢@ScottBoston,我确信这个解决方案有效,但鉴于我有 800 MB 的数据,这种方法非常耗时。
【解决方案2】:

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

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

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)

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

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。

【讨论】:

  • 我不明白你的问题.. 看看代码,它将包含来自dict_2013、dict_2014 和dict_2015 的值。不多也不少。
  • 嗨 jpp,当我使用你的代码时,我收到以下错误:TypeError: cannot concatenate object of type "<class 'list'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
  • 无法复制。对我来说很好。
猜你喜欢
  • 1970-01-01
  • 2014-06-12
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多