【问题标题】:Create a new column in a pandas dataframe, performing conditional equations for if the values are positive or negative在 pandas 数据框中创建一个新列,执行条件方程来判断值是正数还是负数
【发布时间】:2021-09-02 18:33:05
【问题描述】:

我目前有一个熊猫的数据框,它由两列组成,“索引”和“价格”列,如下所示:

我需要创建一个名为“Log”的新列,我想根据“Price”列中的数据是负数还是正数来执行两个单独的操作。对于积极的行,我需要执行以下操作:

df["Log"] = 10**(df['Price'])

如果“价格”列中的数字为负数,请执行以下操作以获取该单元格的绝对值:

df["Log"] = -10**(df['Price'].abs())

能否给我看一个python代码,上面的操作可以在原始pandas数据框上执行,最终结果应该如下所示:

我在下面包含了创建原始数据框的代码:

# Create dataframe 
cars = {'Index': [1,2,3,4,5,6,7,8,9,10], 
        'Price': [2.266021, 2.160644, -2.266021, 2.103899, 2.019323, 2.134563, 2.193423, 2.495643, 2.129344, 2.876545]
        }

df = pd.DataFrame(cars, columns = ['Index', 'Price'])

print (df)

【问题讨论】:

  • np.where()和更复杂的条件操作np.select()
  • 您真的是要对价格求幂并称其为对数吗?这些是彼此的倒数。

标签: python pandas


【解决方案1】:

试试np.where

import numpy as np 

df["Log"] = np.where(df.Price<0, -10**(df['Price'].abs()), 10**(df['Price']))

【讨论】:

    【解决方案2】:

    对于正数,df['Price'].abs()df['Price'] 相同。可以不用条件来表达:

    df["Log"] = np.sign(df['Price']) * (10**df['Price'].abs())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2017-08-30
      • 1970-01-01
      • 2019-08-18
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多