我以这种方式创建了一个字典:数据如下所示:GDS3:ABC_1 ABC_2 BBB_1cat elf 123dog run 456bird burp 789GDS4:ABC_3 ABC_4 BCB_abeer yes 234wine no 543gin yes 743GDS5:ABC_5 ABC_6 BCD_clol yea 543lmao NaN 446asl 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 valuesfor key,val in dict_2014.items(): if key in global_dict: global_dict[key]=[global_dict[key],val] else: global_dict[key]=valfor 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']) 检查。我能做些什么来纠正这个问题?我尝试将列表展平,但仍有问题。
2 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
逻辑中最令人困惑的部分是具有global_dict数据框或列表的值。保持对象类型一致;每次您希望添加一个值时,选择列表并附加到它。
该Python化的解决方案是使用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。
添加回答
举报
0/150
提交
取消