【问题标题】:Pandas multiplying column values under condition熊猫在条件下乘以列值
【发布时间】:2020-11-20 15:47:28
【问题描述】:

不胜感激: 我在列(pandas DF)中有干净的浮点值,如果这个值

    Price    Comission
    10 000   0.1 
    50 000   5 000 
    75 000   0.5

我尝试过这样的事情:(没有成功)

for i in range (df.shape [0]): 
  if (df['Comission'].iloc(i)<1)&(df['Comission'].iloc(i)>0):
    df['Comission'].iloc(i)= df['Comission'].iloc(i)*df['Price'].iloc(i)

有没有办法在 Pandas 中更轻松地进行选择并在选择下进行乘法运算?

【问题讨论】:

    标签: python pandas conditional-statements


    【解决方案1】:

    这是一种方法:

    df = pd.DataFrame({"price": [10, 50, 75], "commision": [0.1, 5.0, 0.5]})
    print(df)
    
    ==>
       price  commision
    0     10        0.1
    1     50        5.0
    2     75        0.5
    
    
    df.loc[df.commision < 1, "commision"] = df.commision * df.price
    print(df)
    
    ==>
       price  commision
    0     10        1.0
    1     50        5.0
    2     75       37.5
    

    【讨论】:

    • df['commision'] * df['price'] 可以工作,分配后不需要loc 命令:)
    • 非常感谢 - 我试过了 - =在乘法中遇到问题 - 因为 2 列是浮点数,所以不能将序列乘以非整数类型的“浮点数”
    • 不确定我是否关注。你有什么错误吗?到底是什么问题?
    • TypeError: can't multiply sequence by non-int of type 'float' 在处理上述异常的过程中,发生了另一个异常:TypeError Traceback (last last call last) /usr/local/lib/ python3.6/dist-packages/pandas/core/ops/array_ops.py in masked_arith_op(x, y, op) 92 if mask.any(): 93 with np.errstate(all="ignore"): --- > 94 result[mask] = op(xrav[mask], yrav[mask]) 95 96 else: TypeError: can't multiply sequence by non-int of 'float'
    • 能否请您运行 df.to_dict(),并将结果添加到问题中?您的数据似乎与我的不同。
    【解决方案2】:

    除了@Roy2012 的回答 (+1),还有另一种方法。

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"Price": [10, 50, 75], "Commision": [0.1, 5.0, 0.5]})
    
    df['Price'] = np.where(
        df['Price'] < 1,                # Condition (price < 1).
        df['Price'] * df['Comission'],  # What to assign to price when condition is true. 
        df['Price']                     # What to assign to price when condition is false.
    )
    

    【讨论】:

    • 你好维克多,谢谢你的回复。我试过你的 np.where - 我不明白为什么它不会比较。两列都转换为浮点数。 df['Бонус агенту']= np.where(df['Бонус агенту']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多