gpt4 book ai didi

python - 在没有 nans 的情况下转置字典

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:29 25 4
gpt4 key购买 nike

users = {"Angelica": {"Blues Traveler": 3.5, "Broken Bells": 2.0, "Norah
Jones": 4.5, "Phoenix": 5.0, "Slightly Stoopid": 1.5, "Pantera": 2.5,
"Metallica": 2.0}, "Bill":{"Blues Traveler": 2.0, "Broken Bells": 3.5,
"Deadmau5": 4.0, "Phoenix": 2.0, "Slightly Stoopid": 3.5, "Metallica": 3.0,
"Norah Jones": 5.0}}

pd.DataFrame(users).transpose().to_dict()
>>>{'Blues Traveler': {'Angelica': 3.5, 'Bill': 2.0}, 'Broken Bells':
{'Angelica': 2.0, 'Bill': 3.5}, 'Deadmau5': {'Angelica': **nan**, 'Bill':
4.0}, 'Metallica': {'Angelica': 2.0, 'Bill': 3.0}, 'Norah Jones':
{'Angelica': 4.5, 'Bill': 5.0}, 'Pantera': {'Angelica': 2.5, 'Bill':
**nan**}, 'Phoenix': {'Angelica': 5.0, 'Bill': 2.0}, 'Slightly Stoopid':
{'Angelica': 1.5, 'Bill': 3.5}}

我想要一个字典,当值为**nan**时,内部字典中的所有键和值都被删除:即'Angelica':**nan**和'Bill':**nan** .

我的代码:

for key in pd.DataFrame(users).transpose().to_dict():
for k in pd.DataFrame(users).transpose().to_dict()[key]:
if math.isnan(pd.DataFrame(users).transpose().to_dict()[key][k]) == False:
listA.append((key, (k, pd.DataFrame(users).transpose().to_dict()
[key][k])))

没有值的期望输出:

>>>{'Blues Traveler': {'Angelica': 3.5, 'Bill': 2.0}, 'Broken Bells':
{'Angelica': 2.0, 'Bill': 3.5}, 'Deadmau5': {'Bill': 4.0}, 'Metallica':
{'Angelica': 2.0, 'Bill': 3.0}, 'Norah Jones': {'Angelica': 4.5, 'Bill':
5.0}, 'Pantera': {'Angelica': 2.5, 'Phoenix': {'Angelica': 5.0, 'Bill':
2.0}, 'Slightly Stoopid': {'Angelica': 1.5, 'Bill': 3.5}}

最佳答案

你可以为此使用一个defaultdict:

from collections import defaultdict

def transpose(dct):
d = defaultdict(dict)
for key1, inner in dct.items():
for key2, value in inner.items():
d[key2][key1] = value
return d

关于python - 在没有 nans 的情况下转置字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21976875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com