Skip to main content
 首页 » 编程设计

Python Pandas .where 有超过 2 个可能的条件输入

2024年10月01日11pander-it

我正在尝试使用 .where pandas dataframe 方法,只有我有超过 2 种可能性(即我有 if、elif、else 而不是默认行为 if else)

请考虑以下数据框:

a1 = np.random.rand(7,2) 
a2 = np.random.randint(0,3,(7,1)) 
grid = np.append(a1, a2, axis=1) 
df = pd.DataFrame(grid) 

我试过了

def test(x): 
    if x[2] == 0: 
        return 5 
    if x[2]==1: 
        return 10 
    if x[2] ==2: 
        return 50 
 
df.where(test) 

但我收到错误消息“系列的真值不明确”。我怀疑这是正确的方向,但我对如何实现它感到困惑。文档说如果条件是可调用的,输入被认为是完整的 df。然而即便如此,它似乎仍将 x[2] 视为整个第 2 列。是否没有办法为该任务实现矢量化操作?是否只能逐行迭代,无论是 iterrows 还是 apply?

这是论坛上的玩具示例,我并不是想在现实生活中做一个简单的 .map 问题。请将“测试”函数保留为一个单独的函数,如果您回答需要传递,因为这是我的困难所在。

请您参考如下方法:

np.random.seed(100) 
a1 = np.random.rand(7,2) 
a2 = np.random.randint(0,3,(7,1)) 
grid = np.append(a1, a2, axis=1) 
df = pd.DataFrame(grid) 
print (df) 
          0         1    2 
0  0.543405  0.278369  2.0 
1  0.424518  0.844776  2.0 
2  0.004719  0.121569  0.0 
3  0.670749  0.825853  0.0 
4  0.136707  0.575093  1.0 
5  0.891322  0.209202  1.0 
6  0.185328  0.108377  1.0 

解决方案 map :

d = {0:5,1:10,2:50} 
df['d'] = df[2].map(d) 
print (df) 
          0         1    2   d 
0  0.543405  0.278369  2.0  50 
1  0.424518  0.844776  2.0  50 
2  0.004719  0.121569  0.0   5 
3  0.670749  0.825853  0.0   5 
4  0.136707  0.575093  1.0  10 
5  0.891322  0.209202  1.0  10 
6  0.185328  0.108377  1.0  10 

另一种解决方案 numpy.where :

df['d'] = np.where(df[2] == 0, 5,  
          np.where(df[2]== 1, 10,  50)) 
 
print (df) 
          0         1    2   d 
0  0.543405  0.278369  2.0  50 
1  0.424518  0.844776  2.0  50 
2  0.004719  0.121569  0.0   5 
3  0.670749  0.825853  0.0   5 
4  0.136707  0.575093  1.0  10 
5  0.891322  0.209202  1.0  10 
6  0.185328  0.108377  1.0  10 

编辑:

对于单独的功能,可以使用 apply带参数 axis=1 用于按 rows 处理 df:

def test(x): 
    #print (x) 
    if x[2] == 0: 
        return 5 
    if x[2]==1: 
        return 10 
    if x[2] ==2: 
        return 50 
 
df['d'] = df.apply(test, axis=1) 
print (df) 
          0         1    2   d 
0  0.543405  0.278369  2.0  50 
1  0.424518  0.844776  2.0  50 
2  0.004719  0.121569  0.0   5 
3  0.670749  0.825853  0.0   5 
4  0.136707  0.575093  1.0  10 
5  0.891322  0.209202  1.0  10 
6  0.185328  0.108377  1.0  10 

但如果需要功能:

def test(x): 
    return np.where(x == 0, 5, np.where(x== 1, 10,  50)) 
 
print (test(df[2])) 
[50 50  5  5 10 10 10]