python - 在也有 None 的 pandas 数据框中查找最大值,Python 3.5

标签 python pandas dataframe

我有一个像这样的 pandas 数据框设置:

     Group1      Group2      Group3
0   0.04058678  0.04282689  0.06680679
1   0.11657916  0.06695174  0.05153584
2   0.08382576  0.03587087  0.08919266
3   0.17477007  0.08141088  0.10727157
4    0.0821453  0.08226264  0.06800853
5   0.15685707        None  0.09467674
6   0.08237982        None  0.14494069
7         None        None  0.14541177
8         None        None  0.12181681
9         None        None  0.17966472
10        None        None   0.1509818

我尝试使用 df.max() 来查找数据框中的最大值,但它不适用于此数据,我认为这是因为某些字段中没有。

我收到此错误:

print(df.max())  
TypeError: unorderable types: float() > str()

如何处理此数据框中的 None 以便获得最大值?

最佳答案

这就是你想要的吗?

最大元素:

In [53]: df.replace('None', np.nan).max().max()
Out[53]: 0.17966472

In [46]: df.replace('None', -np.inf).max()
Out[46]:
Group3    0.179665
dtype: float64

每列最大值:

In [35]: df.replace('None', np.nan).astype(float).max()
Out[35]:
Group1    0.174770
Group2    0.082263
Group3    0.179665
dtype: float64

或最大值的索引

In [28]: df.replace('None', np.nan).astype('float').idxmax()
Out[28]:
Group1    3
Group2    4
Group3    9
dtype: int64

说明:

首先将所有 None 替换为 np.nan (不是数字):

In [56]: df.replace('None', np.nan)
Out[56]:
        Group1      Group2    Group3
0   0.04058678  0.04282689  0.066807
1   0.11657916  0.06695174  0.051536
2   0.08382576  0.03587087  0.089193
3   0.17477007  0.08141088  0.107272
4    0.0821453  0.08226264  0.068009
5   0.15685707         NaN  0.094677
6   0.08237982         NaN  0.144941
7          NaN         NaN  0.145412
8          NaN         NaN  0.121817
9          NaN         NaN  0.179665
10         NaN         NaN  0.150982

查找最大值(返回 pandas 系列):

In [59]: df.replace('None', np.nan).max()
Out[59]:
Group3    0.179665
dtype: float64

In [67]: type(df.replace('None', 0).max())
Out[67]: pandas.core.series.Series

查找系列中的最大值:

In [68]: df.replace('None', 0).max().max()
Out[68]: 0.17966472

关于python - 在也有 None 的 pandas 数据框中查找最大值,Python 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755374/

相关文章:

Python递归生成器性能

python - 使用 pandas 删除停用词

python - 对于 Pandas 的 value_counts() 循环(嵌套)

Python tkinter 标签方向

python - 使用 Dataframe 中的现有列分配列值时出现问题

python - Pandas 按 2 列分组,使用另一列查找增量

python - pandas python 中的欧几里得最小生成树

python - 使用列值对excel文件进​​行排序python

python - 删除 Pandas 中某个字符串后的行

r - 在 R 中的另一个 data.frame 中按权重乘以每列的值