Pandas: Beats 97.44% of users with Pandas
Intuition\n Describe your first thoughts on how to solve this problem. \n\nAdd a new column for gains and losses with negative values if operation is "Buy" or p
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nAdd a new column for gains and losses with negative values if operation is "Buy" or positive values if operation is "Sell". Then group gains and losses by stocks only. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nApply numpy method `np.where(condition, x, y)` to add new column for capital gains and losses. \n\nGroup capital gains by stocks using `pandas.DataFrame.groupby()`  and \nadding the values for capital gains and losses. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport pandas as pd\n\ndef capital_gainloss(stocks: pd.DataFrame) -> pd.DataFrame:\n\n    stocks["capital_gain_loss"] = np.where(stocks["operation"] == \'Buy\', -stocks["price"], stocks["price"])\n\n    return stocks.groupby(by="stock_name", as_index=False).capital_gain_loss.sum()\n\n\n    \n\n    \n    \n```
['Pandas']