python - 从索引值创建列
问题描述
假设我的数据形状如本例所示
idx = pd.MultiIndex.from_product([[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']],
names=['numbers', 'letters'])
col = ['Value']
df = pd.DataFrame(list(range(18)), idx, col)
print(df.unstack())
输出将是
Value
letters a b c
numbers
1 0 1 2
2 3 4 5
3 6 7 8
4 9 10 11
5 12 13 14
6 15 16 17
letters
andnumbers
是索引,Value 是唯一的列
问题是如何将Value
column 替换为名为 index 值的列letters
?
所以我想得到这样的输出
numbers a b c
1 0 1 2
2 3 4 5
3 6 7 8
4 9 10 11
5 12 13 14
6 15 16 17
其中a
,b
和c
是列,数字是唯一的索引。
感谢你的帮助。
解决方案
问题是由您使用unstack
with引起的DataFrame
,而不是pd.Series
df.Value.unstack().rename_axis(None,1)
Out[151]:
a b c
numbers
1 0 1 2
2 3 4 5
3 6 7 8
4 9 10 11
5 12 13 14
6 15 16 17
推荐阅读
- sql - Postgres SQL for 循环计算每月现有用户数
- flutter - 涉及未定义运算符的颤振错误
- git - 如何正确地从 Eclipse 提交?
- aws-lambda - ECS 服务在创建时卡住
- python - 服务器上不存在文件时不显示按钮 - 使用 Flask
- android - Android - 我可以将 libs 、 apk 或代码添加到扩展文件中吗?(ob)
- gsl - 使用 GSL C++ 的 Logistic S 曲线的雅可比矩阵
- algorithm - 阻止仙人掌图上的有向路径
- javascript - 如何防止热键 ` 被添加到 html 表单输入中?
- sass - @mixin 格式可以没有()吗?