访问 pandas 多级索引的“上层名称”

huangapple go评论58阅读模式
英文:

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&#39;m trying to learn how to use Pandas crosstab functionality but I can&#39;t find way to access &#39;upper level name&#39; 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 &#39;0&#39; but want to get list like [&#39;1&#39;,&#39;2&#39;,&#39;5&#39;].

</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:

访问 pandas 多级索引的“上层名称”

&gt;&gt;&gt; df_test2.columns.name
1

&gt;&gt;&gt; df_test2.columns
Index([2, 5, &#39;All&#39;], dtype=&#39;object&#39;, name=1)  # &lt;- 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)

huangapple
  • 本文由 发表于 2023年6月8日 19:22:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定