【问题标题】:Finding a min value among non-numeric columns in pandas在熊猫的非数字列中查找最小值
【发布时间】:2019-07-21 18:35:31
【问题描述】:

考虑以下数据框:

#!/usr/bin/python3.5
import pandas as pd # version 0.23.4
x_df = pd.DataFrame([[1.2, 3.4, 'n', 'a'], [5.6, 'a', 'b', 7.8], 
                    [2.2, 'c', 1.35, 'd'], ['k', 'o', 'b', 'c']], 
                    columns=['A', 'B', 'C', 'D'])

我正在尝试实现每行的最小值(如下所示):

x_df =        A    B     C    D     min
         0  1.2  3.4     n    a    1.2
         1  5.6    a     b  7.8    5.6
         2  2.2    c  1.35    d    1.35
         3    k    o     b    c    nan

我尝试使用:

x_df['min'] = x_df.apply(lambda x: x.min(numeric_only=True), axis=1)

但是这会引发错误:

NotImplementedError: ('Series.min does not implement numeric_only.', 'occurred at index 0')

有没有不使用for 循环或冗长代码的简单方法来实现这一点?

如果这个问题已经得到解答,请指出我并抱歉重复(搜索没有得到我想要的!)

【问题讨论】:

    标签: python python-3.x pandas min


    【解决方案1】:

    简单的方法是先用to_numeric转换成数字,把不能转换的留成NaN,再做min

    df.apply(pd.to_numeric,errors='coerce',axis=1).min(1)
    Out[96]: 
    0    1.20
    1    5.60
    2    1.35
    3     NaN
    dtype: float64
    

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2020-08-09
    • 2022-10-16
    • 1970-01-01
    • 2021-06-23
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多