python - 如何在 Pandas 中使用条件进行计算?

标签 python pandas if-statement

我正在尝试编写一个条件,以便在新列中获取平均每次访问费用。但是,如果访问次数为 0,那么我想改用“1”,这样 Visit_cost 就不是无穷大。

我的方法是抛出一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

df

id    Cost          Visit
2     52            1
3     85            0
4     853           10

df['VISIT_COST'] = [df['Cost']/df['Visit'] if df['Visit'] != 0 else df['Cost']/1]

最终目标:

id    Cost          Visit    VISIT_COST
2     52            1        52
3     85            0        85
4     853           10       85.3

最佳答案

我认为这里最好使用 numpy.where ,因为非常快:

df['VISIT_COST'] = np.where(df['Visit'] != 0, df['Cost']/df['Visit'], df['Cost'])
print (df)
   id  Cost  Visit  VISIT_COST
0   2    52      1        52.0
1   3    85      0        85.0
2   4   853     10        85.3

开箱即用的解决方案 - 将 0 替换为 1 添加转换为整数的 bool 掩码:

df['VISIT_COST'] = df['Cost'].div(df['Visit'].eq(0).astype(int).add(df['Visit']))
print (df)
   id  Cost  Visit  VISIT_COST
0   2    52      1        52.0
1   3    85      0        85.0
2   4   853     10        85.3

详细信息:

print (df['Visit'].eq(0).astype(int))
0    0
1    1
2    0
Name: Visit, dtype: int32

print (df['Visit'].eq(0).astype(int).add(df['Visit']))
0     1
1     1
2    10
Name: Visit, dtype: int64

关于python - 如何在 Pandas 中使用条件进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883194/

相关文章:

android - <remove-project> 如何在 repo list 中工作?

Python:在Python数据框中创建包含列表作为其值的两列的组合

python - 在 pandas 中使用 to_json 时如何保留 DataFrame 索引名称?

Python:Plotly:平行坐标不透明度

命名实体的 Python 自然语言处理

python - 创建带有附加函数的 PyObject 并返回到 Python

Python、Pandas 匹配数据框并指示列表中的结果

java - 即使我将 boolean 值设置为自动为假,如果语句也不起作用

Javascript if else 循环?

Javascript:回文函数?