【问题标题】:pandas get the row-wise minimum value of two or more columnspandas 获得两列或多列的逐行最小值
【发布时间】:2020-09-08 09:49:41
【问题描述】:

如何将两个数据帧的最小值作为 pandas 数据帧方程的一部分引用?我尝试使用不起作用的 python min() 函数。如果这在某处有详细记录,我很抱歉,但我无法找到解决此问题的有效解决方案。我正在寻找类似的东西:

data['eff'] = pd.DataFrame([data['flow_h'], data['flow_c']]).min() *Cp* (data[' Thi'] - data[' Tci'])

我也尝试过使用 pandas min() 函数,也不起作用。

min_flow = pd.DataFrame([data['flow_h'], data['flow_c']]).min()

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

我被这个错误弄糊涂了。数据列只是数字和名称,我不确定索引在哪里起作用。

import pandas as pd
import numpy as np

np.random.seed(365)
rows = 10
flow = {'flow_c': [np.random.randint(100) for _ in range(rows)],
        'flow_d': [np.random.randint(100) for _ in range(rows)],
        'flow_h': [np.random.randint(100) for _ in range(rows)]}
data = pd.DataFrame(flow)

# display(data)
   flow_c  flow_d  flow_h
0      82      36      43
1      52      48      12
2      33      28      77
3      91      99      11
4      44      95      27
5       5      94      64
6      98       3      88
7      73      39      92
8      26      39      62
9      56      74      50

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果您尝试获取两列或多列的逐行mininum,请使用pandas.DataFrame.min 并指定axis=1

    data['min_c_h'] = data[['flow_h','flow_c']].min(axis=1)
    
    # display(data)
       flow_c  flow_d  flow_h  min_c_h
    0      82      36      43       43
    1      52      48      12       12
    2      33      28      77       33
    3      91      99      11       11
    4      44      95      27       27
    5       5      94      64        5
    6      98       3      88       88
    7      73      39      92       73
    8      26      39      62       26
    9      56      74      50       50
    

    【讨论】:

    • 这很好用,但我得到一个 SettingWithCopyWarning...你能更新答案以避免这种情况吗?
    【解决方案2】:

    如果您想获得多列的单个最小值:

    data[['flow_h','flow_c']].min().min()
    

    第一个“min()”计算每列的最小值并返回一个熊猫系列。第二个“min”返回每列最小值中的最小值。

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2018-02-17
      • 2022-12-12
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多