繁体   English   中英

Pandas Dataframe逐行填充新列

[英]Pandas Dataframe row by row fill new column

我试图在Pandas Dataframe上执行逐行操作,如下所示:

df = pd.DataFrame(columns=['Product', 'Price', 'Buy', 'Sell'])
df.loc[len(df.index)] = ["Apple", 1.50, 3, 2]
df.loc[len(df.index)] = ["Banana", 0.75, -8, 4]
df.loc[len(df.index)] = ["Carrot", 2.00, -6, -3]
df.loc[len(df.index)] = ["Blueberry", 0.05, 5, 6]

基本上我想创建一个新的列“比率”,它将价格/买入或价格/卖出分开,具体取决于哪个(买入)或者卖出(卖出)更大。 我不确定怎么做...我会使用apply函数吗?

谢谢!

您可以直接使用列索引( http://pandas.pydata.org/pandas-docs/stable/indexing.html )来比较和过滤比率。

buy_ratio = (abs(df["Buy"])  > abs(df["Sell"])) * df["Price"] / df["Buy"]
sell_ratio = (abs(df["Buy"])  <= abs(df["Sell"])) * df["Price"] / df["Sell"]
df["Ratio"] = buy_ratio + sell_ratio

在这种情况下,

  1. 条件(abs(df["Buy"]) > abs(df["Sell"]))给出0/1值列,具体取决于买入或卖出是否更大。 您将该列乘以Price / Buy。 如果卖出价格很高,则乘法将为零。
  2. 执行Sell的对称操作
  3. 最后,将它们一起添加并使用索引直接设置名为“Ratio”的列。

编辑

以下是使用apply的解决方案 - 首先定义一个在DataFrame的中运行的函数。

def f(row):
  if abs(row["Buy"]) > abs(row["Sell"]):
    return row["Price"] / row["Buy"]
  else:
    return row["Price"] / row["Sell"]

最后,使用apply设置Ratio列。

df["Ratio"] = df.apply(f, axis=1)

这样的事情怎么样? 仔细检查逻辑。

df['Ratio'] = df.apply(
    lambda x: (x.Price / x.Sell) if abs(x.Buy) < abs(x.Sell) else (x.Price / x.Buy),
    axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM