【问题标题】:Returning the max and min values and indexes with Numpy Python使用 Numpy Python 返回最大值和最小值以及索引
【发布时间】:2021-07-09 01:28:28
【问题描述】:

我正在尝试编写一个函数来打印出input.csv 文件中指定列的所有最大值和最小值及其索引。我要返回最大值的列在max_columns 变量中引用,而要返回最小值的列在min_columns 变量中。但是它并没有按预期遍历整个数组值

input.csv 文件:

element,LNPT,SNPT,NLP,NSP,TNT,TPnL,MxPnL,MnPnL,MxU,MxD
[ 2.  2. 30.],0,0,4,4,8,-0.1,-0.0,-0.1,17127,-3
[ 2.  2. 40.],0,0,2,2,4,0.0,-0.0,-0.0,17141,-3
[ 2.  2. 50.],0,0,2,2,4,0.0,-0.0,-0.0,17139,-3
[ 2.  2. 60.],2,0,6,6,12,0.5,2.3,-1.9,17015,-3
[ 2.  2. 70.],1,0,4,4,8,0.3,0.3,-0.0,17011,-3

代码:

my_data = pd.read_csv('input.csv').to_numpy()
max_columns= np.array([1,2,3,7,8,10])
min_columns = np.array([4,5,6,9])

def max_vals():
    results = np.max(my_data[:,max_columns])
    index = np.argmax(results)
    return results, index
    
def min_vals():
    results = np.min(my_data[:,min_columns])
    index = np.argmin(results)
    return results, index

max_values, max_index= max_vals()
min_values, min_index= min_vals()

【问题讨论】:

    标签: python arrays pandas function numpy


    【解决方案1】:

    既然你已经有 pandas 的数据框了,让我们试试 pandas 的方式

    df = pd.read_csv('input.csv')
    max_columns= np.array([1,2,3,7,8,10])
    min_columns = np.array([4,5,6,9])
    

    # max 
    index = df[max_columns].idxmax()
    values = df[max_columns].max()
    

    # min 
    index = df[min_columns].idxmin()
    values = df[min_columns].min()
    

    【讨论】:

    • 它给了我一个错误。 KeyError: "None of [Int64Index([1, 2, 3, 7, 8, 10], dtype='int64')] are in the [columns]"
    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    相关资源
    最近更新 更多