转置多级索引 pandas
Transpose multilevel index pandas
我需要转置来自
的数据帧
Month Year Count
1 2013 4456
2014 3321
2015 3316
2016 6798
2 2013 4123
2014 4490
2015 5689
依此类推变成一个看起来像
Year 1 2
2013 4456 4123
2014 3321 4490
2015 3316 5689
2016 6798 NaN
各种尝试,包括查看 MultiLevel index to columns : getting value_counts as columns in pandas
没工作过
编辑时 - unstack 方法不起作用(或者我不知道如何正确使用它)但是 reset_index 的枢轴工作得很好。
我的第一个问题似乎是对索引和多索引的完全误解,因为 Month Year 是一个多索引(根据查看数据框)但是任何尝试使用 df['Month'] 或其他组合总是失败。
真的很想在这里得到一些帮助。
您要找的函数是pivot
。您可能需要先使用 reset_index
。
df = df.reset_index().pivot('Year', 'Month', 'Count')
或者,您可以使用 unstack
函数,如 this answer。
我需要转置来自
的数据帧Month Year Count
1 2013 4456
2014 3321
2015 3316
2016 6798
2 2013 4123
2014 4490
2015 5689
依此类推变成一个看起来像
Year 1 2
2013 4456 4123
2014 3321 4490
2015 3316 5689
2016 6798 NaN
各种尝试,包括查看 MultiLevel index to columns : getting value_counts as columns in pandas 没工作过
编辑时 - unstack 方法不起作用(或者我不知道如何正确使用它)但是 reset_index 的枢轴工作得很好。
我的第一个问题似乎是对索引和多索引的完全误解,因为 Month Year 是一个多索引(根据查看数据框)但是任何尝试使用 df['Month'] 或其他组合总是失败。
真的很想在这里得到一些帮助。
您要找的函数是pivot
。您可能需要先使用 reset_index
。
df = df.reset_index().pivot('Year', 'Month', 'Count')
或者,您可以使用 unstack
函数,如 this answer。