Pandas 中的 IF 语句:使用来自一列 (A) 的值到来自不同列(B 或 C)的 select 值并将其存储在一个单独的列中 (D)

IF Statement in Pandas: Using values from one column (A) to select values from different columns (B or C) an store it in one separate column (D)

我的问题是:如何用 Pandas 简化我的 table,只得到一列包含所选值(三列应该是一列)。

Name    Selection   Active  Inactive
A       active      0       0.9
B       active      1       0.8
C       inactive    2       0.7
D       inactive    3       0.6
E       active      4       0.5

点赞IF Selection = 'active' THEN Active ELSE Inactive as Selected_Value获得以下结果:

Name    Selected_Value
A       0
B       1
C       0.7
D       0.6
E       4 

她是你如何使用numpy.where():

import pandas as pd
import numpy as np
df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E'],
                   'Selection': ['active', 'active', 'unactive', 'unactive', 'active'],
                   'Active': [0, 1, 2, 3, 4],
                   'Unactive': [0.9, 0.8, 0.7, 0.6, 0.5]})

df['Selected_Value'] = np.where(df['Selection']=='active', # If the element for the Selection column is active
                                df['Active'], # The element of the Selected_Value column of that index will be the element from the Active column
                                df['Unactive']) # Else, the element of the Selected_Value column of that index will be the element from the Unactive column
                           
print(df['Selected_Value'])

输出:

0    0.0
1    1.0
2    0.7
3    0.6
4    4.0
Name: Selected_Value, dtype: float64

下面的代码应该可以为您提供所需的内容。

df.loc[df['Selection'] == 'active','Selected_Value'] = df['Active']
df.loc[df['Selection'] == 'unactive','Selected_Value'] = df['Unactive']