Skip to main content
 首页 » 编程设计

Python Pandas if/else 语句

2025年05月04日1352php

我正在尝试使用 pandas 编写嵌套的 if/else 语句,但在 pandas 中使用 if 语句不是很好。请找到正在处理的示例 CSV 数据和我目前编写的示例代码片段。

df:

t1   
8 
1134 
0 
119 
122 
446 
21 
0 
138  
0 

当前的 if/else 语句逻辑:

import pandas as pd 
 
df = pd.read_csv('file.csv', sep=';') 
 
def get_cost(df): 
    t_zone = 720 
    max_rate = 5.5 
    rate = 0.0208 
    duration = df['t1'] 
 
    if duration < t_zone: 
        if(duration * rate) >= max_rate: 
            return max_rate 
        else: 
            return(duration * rate) 
    else: 
        if duration >= 720: 
            x = int(duration/720) 
            y = ((duration%720) * rate) 
            if y >= max_rate: 
                return((x * max_rate) + max_rate) 
            else: 
                return((x * max_rate) + y) 
 
cost = get_cost(df) 

此片段引发了一个ValueError: The truth value of a Series is ambiguous 错误。如果有人有更好的解决方案或可以帮助将此 if/else 语句翻译成更适合 pandas 的方式,那就太棒了!

请您参考如下方法:

除非绝对必要,否则在 pandas 中使用循环和 if 语句效率不高。这是一个完全矢量化的 100% pandas 解决方案:

import numpy as np # Needs numpy, too 
x = df['t1'] // 720 * max_rate # Note the use of //! 
y = df['t1'] %  720 * rate 
df['cost'] = np.where(df['t1'] < t_zone,  
                      np.minimum(df['t1'] * rate, max_rate), 
                      np.minimum(y,               max_rate) + x)