python - 引用和计数属于层次结构的列
问题描述
我希望能够引用更高层次的列,并能够计算列数并列出它拥有的列的名称。
这是数据集:
import pandas as pd
import numpy as np
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=arrays)
这是输出:
bar baz foo qux
one two one two one two one two
A 0.050343 -0.525009 0.126593 -0.332575 -1.233224 0.415279 1.097570 0.096461
B 2.371400 -0.184967 -0.470547 2.203325 -0.914778 0.392034 0.398723 1.047543
C 0.977506 1.606047 -0.993077 -0.804615 0.654538 -0.099860 0.679309 -1.313231
我试图了解如何查找属于某个层次结构的列数(例如bar
.
我的尝试似乎不起作用,因为我期望 2 作为print(len())
函数的输出和函数[one, two]
的输出print()
。
尝试1:
print(len(df.columns))
print(df.columns)
8
MultiIndex([('bar', 'one'),
('bar', 'two'),
('baz', 'one'),
('baz', 'two'),
('foo', 'one'),
('foo', 'two'),
('qux', 'one'),
('qux', 'two')],
)
尝试2:
print(len(df.columns[1]))
print(df.columns[1])
2
('bar', 'two')
尝试 3:
print(len(df.columns['bar'])
print(df.columns['bar'])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
所需的输出将是:
2
['one','two']
解决方案
普通选择呢?:
>>> df['bar']
one two
A -0.671483 0.349299
B 0.475603 0.576552
C -0.141044 -1.063308
>>> df['bar'].shape
(3, 2)
>>> df['bar'].columns
Index(['one', 'two'], dtype='object')
推荐阅读
- html - 有没有办法让平行四边形 div 适合整个页面宽度和同一行?
- excel - 以特定方式反转文本
- c++ - 基类不可访问错误,为什么私有继承会这样做?
- javascript - JavaScript中的字符串到整数对象散列
- node.js - 如何使用 node.js 在 Redis 中同步 mongoDB 数据库的更改
- mysql - 如何将ip地址插入mysql
- html-framework-7 - Framework7 已经初始化(React)
- qt5 - bitbake:如何恢复编译
- python-3.x - 如何知道用户是否在 wxPyhton 中更改了 AuiNotebook 的选项卡顺序?
- php - 带有准备好的语句的 mysqli_stmt_num_rows 不返回行数