当满足 for 循环中的条件时,将一行中的值附加到同一行但在新列中

Appending value from a row onto the same row but in a new column when condition in for loop is met

我需要将 R2ESL 或 MCL 列中较小的数值附加到新列 Lesser Value 中,用于每一行(例如 A、B、C)。

例如,对于参数 A,值为 7 的 MCL 小于值为 10 的 R2ESL。我想将 7 放入新列(较小的值),但在同一行 (A) 上。

到目前为止,我只能在 for 循环中使用 'append' 来附加限制条件列。

param R2ESL MCL Limiting Criteria Lesser Value
A 10 7 MCL 7
B 100 150 R2ESL 100
C 55 55 equal 55
excel_df = pd.read_excel('ESLs_MCL_Comparison_copy.xls')

# Changing data type in columns to float
R2ESL_float = [float(item) for item in R2ESL]
print(R2ESL_float)

MCL_float = [float(item) for item in MCL]
print(MCL_float)

# Comparing the values in each column
result = []
result2 = []
for (R2ESL_float, MCL_float) in zip(R2ESL_float, MCL_float):
    if R2ESL_float > MCL_float:
        result.append("R2ESL")
        # result2.append(param_row_value_R2ESL) <-- Need help here
    elif R2ESL_float < MCL_float:
        result.append("MCL")
        # result2.append(param_row_value_MCL) <-- Need help here
    elif R2ESL_float == MCL_float:
        result.append("Equal")
        # result2.append("param_row_value_MCL_or_R2ESL") <-- Need help here
    else:
        result.append("null")
        # result2.append("null")

excel_df["Limiting Criteria"] = result
# excel_df["Lesser Value"] = result2
print(excel_df)

我是python的新手,才学了几个星期,所以请解释清楚。

v1, v2 = df['R2ESL'].values, df['MCL'].values
df['Limiting Criteria'] = np.select([v1==v2, v1<v2, v1>v2], ['equal', 'R2ESL', 'MCL'])

# Determine the lesser value
df['Lesser Value'] = df[['R2ESL', 'MCL']].min(axis=1)

例如(这是从交互式 Python 会话中复制的):

>>> df
  param  R2ESL  MCL
0     A     10    7
1     B    100  150
2     C     55   55


>>> v1, v2 = df['R2ESL'].values, df['MCL'].values
>>> df['Limiting Criteria'] = np.select([v1==v2, v1<v2, v1>v2], ['equal', 'R2ESL', 'MCL'])
>>> df
  param  R2ESL  MCL Limiting Criteria
0     A     10    7               MCL
1     B    100  150             R2ESL
2     C     55   55             equal


>>> df['Lesser Value'] = df[['R2ESL', 'MCL']].min(axis=1)
>>> df
 param  R2ESL  MCL Limiting Criteria  Lesser Value
0     A     10    7               MCL             7
1     B    100  150             R2ESL           100
2     C     55   55             equal            55

它的作用:

对于Limiting Criteria

  1. .values returns Series(或DataFrame)后面的numpy数组
  2. [v1==v2, v1<v2, v1>v2] 创建一个包含三个仅包含布尔值(所谓的“掩码”)的 numpy 数组的列表。第一个包含 True,其中 v1v2 中的项目相等,否则为 False。第二个包含 True,其中 v1 中的值小于 v2 中的值。第三个包含 True,其中 v1 中的值大于 v2.
  3. np.select 接受两个参数:一个“条件”列表(实际上是掩码)和一个值列表,并将每个条件中的 True 替换为值列表中的相应值

对于Lesser Value

  1. df[['R2ESL', 'MCL']] 基本上选择原始数据帧的子集数据帧,只有列 R2ESLMCL.
  2. .min(axis=1) 获取每行所有列的最小值。