擅长:python、mysql、java
<p>试试这个</p>
<pre><code>grp = df.groupby(["Year", "Month", "Project", "Account"]).agg({"Value":"sum"}).reset_index()
costdf = grp.groupby(["Year", "Month", "Project"]).apply(lambda x: (x[x["Account"]=="Revenue"]["Value"].values[0] - x[x["Account"]=="Profit"]["Value"].values[0])).reset_index()
costdf.columns = ["Year", "Month", "Project","Value"]
costdf["Account"] = "Cost"
costdf = costdf[df.columns]
df = pd.concat([df,costdf])
</code></pre>