【发布时间】:2021-09-22 10:58:28
【问题描述】:
构建 3-d pandas 数据框后,我很难仅访问特定列。
场景如下:
head = ["h1", "h2"]
cols = ["col_1", "col_2", "col_3"]
heads = len(cols) * [head[0]] + len(cols) * [head[1]] # -> ['h1','h1','h1','h2','h2','h2']
no_of_rows = 4
A = np.array(heads)
B = np.array(cols * len(head)) # -> ['col_1','col_2','col_3','col_1','col_2','col_3']
C = np.array([np.zeros(no_of_rows)] * len(head) * len(cols)) # -> shape=(6, 4)
df = pd.DataFrame(data=C.T,
columns=pd.MultiIndex.from_tuples(zip(A,B)))
屈服
h1 h2
col_1 col_2 col_3 col_1 col_2 col_3
0 0.0 0.0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0
3 0.0 0.0 0.0 0.0 0.0 0.0
现在我想得到例如全部 col_1,表示h1 的col_1 和h2 的col_1。输出应该是这样的
h1 h2
col_1 col_1
0 0.0 0.0
1 0.0 0.0
2 0.0 0.0
3 0.0 0.0
对我如何访问这两列有什么建议吗?
【问题讨论】: