Jef*_*iao 3 python dataframe pandas
我有一个输入 dict-of-string-to-list,列表的长度可能不同。
d = {'b': [2,3], 'a': [1]}
Run Code Online (Sandbox Code Playgroud)
当我这样做时:df = pd.DataFrame(data=d)
,我看到ValueError: arrays must all be same length
问题:如何在创建 df 时使用默认值(例如 0)填充缺失值?
创建 df 的原因是为了得到最终结果:
{'b': 3}
而3
是列表中所有数字的最大值。
您可以使用DataFrame.from_dict
设置orient
toindex
以便将字典的键用作索引并将缺失值设置为NaN
。然后只需填写NaNs
using.fillna
和 transpose 将键设置为列:
pd.DataFrame.from_dict(d, orient='index').fillna(0).T
b a
0 2.0 1.0
1 3.0 0.0
Run Code Online (Sandbox Code Playgroud)