<p>您只需执行3个步骤即可轻松完成此操作:</p>
<ol>
<li>将数据框分为两部分:“常规数据”(我们希望将其作为一个系列)和更具体的数据。现在,每个数据帧都包含相同类型的信息</李>
<li>问题的关键部分是:重新组织数据。您所需要的只是<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><strong>pandas pivot</strong></a>函数。它正是你所需要的</李>
<li>将常规信息和数据透视重新添加到一起</李>
</ol>
<pre><code># Split Data
general = df[df.Group == "0"].set_index("Name")["Value"].copy()
main_df = df[df.Group != "0"]
# Pivot Data
result = main_df.pivot(index="Group", columns=["Name"],
values=["Value", "Ccy"]).fillna("")
result.columns = [f"{c[1]}_{c[0]}" for c in result.columns]
# Create a data frame that has an identical row for each group
general_df = pd.DataFrame([general]*3, index=result.index)
general_df.columns = [c + "_Value" for c in general_df.columns]
# Merge the data back together
result = general_df.merge(result, on="Group")
</code></pre>
<p>上面给出的结果没有给出您想要的确切列顺序,因此您必须使用</p>
<pre><code>final_cols = ["ID_Value", "Country_Value", "IBAN_Value",
"Dan_age_Value", "Dan_Age_Ccy", "Dan_city_Value",
"Dan_city_Ccy", "Dan_sex_Value"]
result = result[final_cols]
</code></pre>