将不同大小的列表的Dict转换为d

2024-05-10 01:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力使用pd.DataFrame(Dict)将dict转换为df,但是,我得到了一个错误ValueError: arrays must all be same length。有人能解释一下吗。有没有什么方法可以将Dict转换成“Value”中不同大小的Dict?你知道吗

Dict= {'Country': [], 'Organization ': [], 'Education ': [], 'City ': ['Toronto']}

如果您能提供任何提示,我们将不胜感激。 非常感谢, R


Tags: 方法dataframedfvalue错误bealllength
1条回答
网友
1楼 · 发布于 2024-05-10 01:23:43

如果要将前3列保留为空,则需要空格或np.nan而不是空列表:

Dict= {'Country': [np.nan],
 'Organization ': [np.nan],
 'Education ': [np.nan],
 'City ': ['Toronto']}

print(pd.DataFrame(Dict))
    Country  Organization   Education     City 
0      NaN            NaN         NaN  Toronto

所以用np.nan替换空列表:

Dict= {'Country': [],
'Organization ': [],
 'Education ': [],
 'City ': ['Toronto']}

df=pd.DataFrame({k: np.nan if not v else v for k, v in Dict.items()})
print(df)  

   Country  Organization   Education     City 
0      NaN            NaN         NaN  Toronto

相关问题 更多 >