英文:
Accessing 'upper level name' of pandas multi-index
问题
I can help with the translation:
我正在尝试学习如何使用Pandas的crosstab功能,但我找不到访问crosstab生成的多级索引数据帧的“上级名称”的方法。简单示例:
```python
df_test = pd.DataFrame.from_dict({'A': [1, 2, 3], 'B': [4, 5, 6]}, orient='index')
df_test2 = pd.crosstab(df_test[0], df_test[1], margins=True)
print(df_test2.index.names)
Index.names只给我返回'0',但我想要得到类似['1','2','5']的列表。
<details>
<summary>英文:</summary>
I'm trying to learn how to use Pandas crosstab functionality but I can't find way to access 'upper level name' of multi-index dataframe that crosstab produces. Simple example:
df_test = pd.DataFrame.from_dict({'A': [1, 2, 3], 'B': [4, 5, 6]}, orient='index')
df_test2 = pd.crosstab(df_test[0], df_test1, margins=True)
print(df_test2.index.names)
Index.names gives me only '0' but want to get list like ['1','2','5'].
</details>
# 答案1
**得分**: 3
您的数据框产生了以下结果:
[![在此输入图像描述][1]][1]
```python
>>> df_test2.columns.name
1
>>> df_test2.columns
Index([2, 5, 'All'], dtype='object', name=1) # <- 注意 name 为 1
英文:
Your dataframe produces the following result:
>>> df_test2.columns.name
1
>>> df_test2.columns
Index([2, 5, 'All'], dtype='object', name=1) # <- Note the 1 as name
答案2
得分: 1
我没有理解'1'是列索引的名称。所以这样做就得到了我想要的结果:
test_list = df_test2.columns.to_list()
test_list.insert(0, df_test2.columns.name)
英文:
I didn't understand that '1' was a name of column index. So this produced what I wanted:
test_list = df_test2.columns.to_list()
test_list.insert(0, df_test2.columns.name)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论