将数据框列值透视为新列并将剩余列透视为行

Jon*_*nny -1 python pivot dataframe pandas

Year值成为列,其余列成为行。有任何想法吗?

数据:

   Year Propertyval Cumulative
0  1    1224000.00  24000.00
1  2    1248480.00  48480.00
2  3    1273449.60  73449.60
Run Code Online (Sandbox Code Playgroud)

所需格式:

   Desc          1           2           3
0  Propertyval   1248480.00  1273449.60  1273449.60
1  Cumulative    24000.00    48480.00    73449.60
Run Code Online (Sandbox Code Playgroud)

int*_*gar 5

这对你有用吗?

import pandas as pd
df = pd.read_clipboard()
df_new = df.pivot_table(columns="Year", values=["Propertyval", "Cumulative"])
Run Code Online (Sandbox Code Playgroud)

更新:如果您还想重置索引并更改列名,那么这会更准确:

import pandas as pd
df = pd.read_clipboard()
df_new = df.pivot_table(columns="Year", values=["Propertyval", "Cumulative"]).reset_index().rename(columns={'index':'Desc'}).rename_axis(None, axis=1)
Run Code Online (Sandbox Code Playgroud)

感谢您的提示@Tobias PG