在Pandas中创建DataFrame时填充默认0 [英] Fill with default 0's when creating a DataFrame in Pandas
问题描述
我有一个输入到列表的字符串字典,列表的长度可能不同.
I have an input dict-of-string-to-list with possibly different lengths for the list.
d = {'b': [2,3], 'a': [1]}
当我这样做时:df = pd.DataFrame(data=d)
,
我看到 ValueError:数组的长度必须相同
when I do: df = pd.DataFrame(data=d)
,
i'm seeing ValueError: arrays must all be same length
问题:创建df时如何用默认值(例如0)填充缺失值?
Question: How do i fill the missing values with default (e.g. 0) when creating the df?
创建df的原因是获得以下最终结果:
{'b': 3}
The reason to create the df is to get the final result of:
{'b': 3}
3
是列表中所有数字的最大值.
whereas 3
is the max of all numbers in the lists.
推荐答案
您可以使用 .fillna
并转置以将键设置为列:
You can use DataFrame.from_dict
setting orient
to index
so the keys of the dictionary are used as indices and the missing values are set to NaN
. Then simply fill NaNs
using .fillna
and transpose to set the keys as columns:
pd.DataFrame.from_dict(d, orient='index').fillna(0).T
b a
0 2.0 1.0
1 3.0 0.0
这篇关于在Pandas中创建DataFrame时填充默认0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!