将数据框列值转换为新列并将其余列转换为行

Pivot dataframe column values into new columns & pivot the remaining columns to rows

Year 值成为列,其余列成为行。有什么想法吗?

数据:

   Year Propertyval Cumulative
0  1    1224000.00  24000.00
1  2    1248480.00  48480.00
2  3    1273449.60  73449.60

所需格式:

   Desc          1           2           3
0  Propertyval   1248480.00  1273449.60  1273449.60
1  Cumulative    24000.00    48480.00    73449.60

可能有更简单的方法,但这些步骤应该可以解决问题。

# Read the sample dataframe from clipboard
df = pd.read_clipboard()
# Transpose the index and columns
df = df.T
# Rename the column based on first row
df.rename(columns=df.iloc[0].astype(int), inplace = True)
# Drop the first row
df.drop(df.index[0], inplace = True)
# Reset index
df = df.reset_index()
# Rename previous index column
df = df.rename(columns={'index':'Desc'})

df

输出:

    Desc        1.0         2.0         3.0
0   Propertyval 1224000.0   1248480.0   1273449.6
1   Cumulative  24000.0     48480.0     73449.6

这对你有用吗?

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

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

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)

感谢@Tobias P.G. 的提示