将列中的值作为新列名时出错?
Error when making value in column as a new column name?
我正在尝试为“年”内的每个“子市场”生成平均“1_Bed_Effective_Rent_Per_Unit_Modified”。我用这条线为每个“子市场”取了一年中四个季度的平均值
df = county_rental_df.groupby(["Year", "SubMarkets"])["1_Bed_Effective_Rent_Per_Unit_Modified"].mean()
并将此输出作为一个系列
Year
SubMarkets
1_Bed_Effective_Rent_Per_Unit_Modified
2000
1 Ward
1148.50
2 Ward
2683.00
2001
1 Ward
896.00
2 Ward
2107.50
然后我使用这个df_1 = df.to_frame()
将该系列制作成数据框
如上所示,年份栏每年只打印一次年份table。
我想要的最终产品的样子是
SubMarkets
2000
2001
1 Ward
1148.50
896.00
2 Ward
2683
2107.50
所以我使用了这一行 df_1_2 = df_1.pivot(index='SubMarkets', columns='Year', values='1_Bed_Effective_Rent_Per_Unit_Modified')\.reset_index()
并且我得到了一个错误“KeyError:'SubMarkets'”。我该如何解决这个问题以获得我想要的输出?
您需要在 pivot
之前重置 df_1
的索引
df_1 = df_1.reset_index()
df_1_2 = df_1.pivot(index='SubMarkets', columns='Year', values='1_Bed_Effective_Rent_Per_Unit_Modified')
我正在尝试为“年”内的每个“子市场”生成平均“1_Bed_Effective_Rent_Per_Unit_Modified”。我用这条线为每个“子市场”取了一年中四个季度的平均值
df = county_rental_df.groupby(["Year", "SubMarkets"])["1_Bed_Effective_Rent_Per_Unit_Modified"].mean()
并将此输出作为一个系列
Year | SubMarkets | 1_Bed_Effective_Rent_Per_Unit_Modified |
---|---|---|
2000 | 1 Ward | 1148.50 |
2 Ward | 2683.00 | |
2001 | 1 Ward | 896.00 |
2 Ward | 2107.50 |
然后我使用这个df_1 = df.to_frame()
如上所示,年份栏每年只打印一次年份table。
我想要的最终产品的样子是
SubMarkets | 2000 | 2001 |
---|---|---|
1 Ward | 1148.50 | 896.00 |
2 Ward | 2683 | 2107.50 |
所以我使用了这一行 df_1_2 = df_1.pivot(index='SubMarkets', columns='Year', values='1_Bed_Effective_Rent_Per_Unit_Modified')\.reset_index()
并且我得到了一个错误“KeyError:'SubMarkets'”。我该如何解决这个问题以获得我想要的输出?
您需要在 pivot
之前重置df_1
的索引
df_1 = df_1.reset_index()
df_1_2 = df_1.pivot(index='SubMarkets', columns='Year', values='1_Bed_Effective_Rent_Per_Unit_Modified')