如何在连接两个数据帧后访问数据帧索引:一个具有多索引,一个没有



我想访问数据帧中的列/索引,该列/索引是两个数据帧之间的串联,一个具有多索引,另一个没有。问题在代码中。

import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.ones((2, 2)), columns=["a", "b"])
df2_cols = pd.MultiIndex.from_tuples([("c", 1), ("d", 2)])
df2 = pd.DataFrame(data=np.ones((2, 2)), columns=df2_cols)
df = pd.concat([df1, df2], axis=1)
print(df)

输出:

a    b  (c, 1)  (d, 2)
0  1.0  1.0     1.0     1.0
1  1.0  1.0     1.0     1.0

现在访问新数据帧的不同部分:

df1.loc[:, "a"]  # works
df.loc[:, "a"]   # works
df2.loc[:, ("c", 1)] # works
df.loc[:, ("c", 1)] # crashes -> is it possible to access this column using loc?
# even this crashes, where I am directly using the name provided by the dataframe column:
df.loc[:, df.columns[2]]

错误:

键错误:"[索引(['c',1],dtype='object'(]都不在[列]";

df[("c", 1)] # interestingly works
df = df.T
df.loc[("c", 1)] # crashes -> is it possible to access this index using loc?

我知道我可以使用iloc或这里的选项:将多索引数据帧与单索引数据帧连接会破坏多索引格式,从而确保多索引格式保留在新的数据帧中。但我想知道如果没有它是否可能。

对我来说似乎是个bug。

你可以作弊并使用2D切片:

df.loc[:, [('c', 1)]]

输出:

(c, 1)
0     1.0
1     1.0

您可以正确分配:

df.loc[:, [('c', 1)]] = [8,9]

更新的数据帧:

a    b  (c, 1)  (d, 2)
0  1.0  1.0       8     1.0
1  1.0  1.0       9     1.0

如果你需要一个系列:

df.loc[:, [('c', 1)]].squeeze()

输出:

0    1.0
1    1.0
Name: (c, 1), dtype: float64

相关内容

最新更新