python pandas dataframe if else 不遍历数据框

标签 python numpy pandas dataframe

我想向 df 添加一列。这个新 df 的值将取决于其他列的值。例如

dc = {'A':[0,9,4,5],'B':[6,0,10,12],'C':[1,3,15,18]}
df = pd.DataFrame(dc)
   A   B   C
0  0   6   1
1  9   0   3
2  4  10  15
3  5  12  18

现在我想添加另一列 D,其值将取决于 A、B、C 的值。 因此,例如,如果正在遍历 df,我会这样做:

for row in df.iterrows():
    if(row['A'] != 0 and row[B] !=0):
         row['D'] = (float(row['A'])/float(row['B']))*row['C']
    elif(row['C'] ==0 and row['A'] != 0 and row[B] ==0):
         row['D'] == 250.0
    else:
         row['D'] == 20.0 

有没有办法在没有 for 循环或使用 where () 或 apply () 函数的情况下执行此操作。

谢谢

最佳答案

apply 应该适合你:

In [20]: def func(row):
            if (row == 0).all():
                return 250.0
            elif (row[['A', 'B']] != 0).all():
                return (float(row['A']) / row['B'] ) * row['C']
            else:
                return 20
       ....:     


In [21]: df['D'] = df.apply(func, axis=1)

In [22]: df
Out[22]: 
   A   B   C     D
0  0   6   1  20.0
1  9   0   3  20.0
2  4  10  15   6.0
3  5  12  18   7.5

[4 rows x 4 columns]

关于python pandas dataframe if else 不遍历数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23482304/

相关文章:

Python + Ubuntu Linux + nohup 错误 : [1]+ Exit

python - 如何在 python 中为每一对分开做矩阵向量内积?

python - 如何正确地将小时数添加到 pandas.tseries.index.DatetimeIndex?

python - 为什么在 'and' 、 'or' 等处没有 python 隐式续行?

python - 为什么 numpy 的 where 操作比 apply 函数快?

python - Numpy 多维数组赋值未知登录错误

python - 为表示 3D 点坐标的两个 2D 数组创建 bool 掩码

python - 如何创建用零初始化的元组矩阵

python - Pandas 检查多列中的值是否存在于其他列中

python - 使用 groupby 进行字数统计然后使用 python 循环时出现问题