[英]Pandas Dataframe row by row fill new column
I am trying to perform a row by row operation on a Pandas Dataframe as such: 我试图在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]
Basically I want to create a new column "Ratio" that divides Price/Buy or Price/Sell, depending on which abs(buy) or abs(sell) is greater. 基本上我想创建一个新的列“比率”,它将价格/买入或价格/卖出分开,具体取决于哪个(买入)或者卖出(卖出)更大。 I am not really sure how to do this...would I use an apply function?
我不确定怎么做...我会使用apply函数吗?
Thanks! 谢谢!
You can directly use column indexing ( http://pandas.pydata.org/pandas-docs/stable/indexing.html ) to compare and filter ratios. 您可以直接使用列索引( 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
In this case, 在这种情况下,
(abs(df["Buy"]) > abs(df["Sell"]))
gives a 0/1 valued column depending on whether buy or sell is greater. (abs(df["Buy"]) > abs(df["Sell"]))
给出0/1值列,具体取决于买入或卖出是否更大。 You multiply that column by Price/Buy. Edit 编辑
Here is the solution using apply - First define a function operating in rows of the DataFrame. 以下是使用apply的解决方案 - 首先定义一个在DataFrame的行中运行的函数。
def f(row):
if abs(row["Buy"]) > abs(row["Sell"]):
return row["Price"] / row["Buy"]
else:
return row["Price"] / row["Sell"]
Finally, set the Ratio
column appropriately using apply. 最后,使用apply设置
Ratio
列。
df["Ratio"] = df.apply(f, axis=1)
What about something like this? 这样的事情怎么样? Double check the logic.
仔细检查逻辑。
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.