假设我有一个这样的列表字典:

mydict={10:[],20:[],30:[],40:[],50:[1],60:[],70:[1],80:[7, 2, 7, 2, 2, 7, 2],90:[5, 2, 2, 6, 2, 3, 1, 2, 1, 2],...}

我要计算:dict中的每个列表的最小值,最大值,中位数,第一和第三四分位数。我先尝试了minmax,如下所示:

mins_mydict={k:min(v) for k,v in mydict.items()}

maxes_mydict={k:max(v) for k,v in mydict.items()}

但出现此错误:ValueError: min() arg is an empty sequence。与max相同。是因为我的某些列表为空吗?

如何创建检查len(list)=0的异常?

最佳答案

In [4]: mydict={10:[],20:[],30:[],40:[],50:[1],60:[],70:[1],80:[7, 2, 7, 2, 2, 7, 2],90:[5, 2, 2, 6, 2, 3, 1, 2, 1, 2]}

In [5]: import pandas as pd

In [6]: df = pd.DataFrame.from_dict(dict([ (k, pd.Series(v)) for k,v in mydict.items() ]))

In [7]: print(df.min())
10    NaN
20    NaN
30    NaN
40    NaN
50    1.0
60    NaN
70    1.0
80    2.0
90    1.0
dtype: float64

In [8]: df.max()
Out[8]:
10    NaN
20    NaN
30    NaN
40    NaN
50    1.0
60    NaN
70    1.0
80    7.0
90    6.0
dtype: float64

In [9]: df.median()
Out[9]:
10    NaN
20    NaN
30    NaN
40    NaN
50    1.0
60    NaN
70    1.0
80    2.0
90    2.0
dtype: float64

In [10]: df.quantile([.1, .3])
Out[10]:
     10  20  30  40   50  60   70   80   90
0.1 NaN NaN NaN NaN  1.0 NaN  1.0  2.0  1.0
0.3 NaN NaN NaN NaN  1.0 NaN  1.0  2.0  2.0

关于python - Python:如何从列表的字典中计算最小,最大,中位数,第一和第三四分位数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36446960/

10-12 22:11