【发布时间】:2020-04-21 00:52:08
【问题描述】:
我有一个包含产品、操作、数量和价格的 Pandas DataFrame。如果动作是“卖出”,我需要考虑产品的价格为 0 并反转数量。
我尝试过的:
import pandas as pd
def my_function(df):
kwargs = {
"quantity": lambda x: -x["quantity"] if "SELL" in str(x["action"]) else x["quantity"],
"price (usd)": lambda x: 0 if "SELL" in str(x["action"]) else x["price (usd)"],
}
return df.assign(**kwargs)
input_df = pd.DataFrame({"product": ["APPLE", "APPLE", "BANANA"],
"action": [" SELL ", " BUY ", " SELL "],
"quantity": [1, 2, 3],
"price (usd)": [3, 5, 8],
})
result_df = my_function(input_df)
expected_df = pd.DataFrame({"product": ["APPLE", "APPLE", "BANANA"],
"action": [" SELL ", " BUY ", " SELL "],
"quantity": [-1, 2, -3],
"price (usd)": [0, 5, 0],
})
不知何故,我的 lambda 表达式中的条件总是返回 True,我也认为这可能是一种更简单的方法。有什么想法吗?
【问题讨论】:
标签: python python-3.x pandas lambda