Pandas 数据帧通用列值
是否有一种通过DF['ColName']获取列值的一致方法,包括索引列?如果“ColName”是一个索引列,则会得到KeyError 非常不方便的是,每次需要确定传入的列是否为索引列时,都要对其进行不同的处理Pandas 数据帧通用列值,pandas,Pandas,是否有一种通过DF['ColName']获取列值的一致方法,包括索引列?如果“ColName”是一个索引列,则会得到KeyError 非常不方便的是,每次需要确定传入的列是否为索引列时,都要对其进行不同的处理 谢谢。考虑数据帧df df = pd.DataFrame( dict( A=[1, 2, 3], B=[4, 5, 6], C=['x', 'y', 'z'], ), pd.MultiIndex.from_tuples
谢谢。考虑数据帧
df
df = pd.DataFrame(
dict(
A=[1, 2, 3],
B=[4, 5, 6],
C=['x', 'y', 'z'],
),
pd.MultiIndex.from_tuples(
[
('cat', 'red'),
('dog', 'blue'),
('bird', 'yellow')
],
names=['species', 'color']
)
)
print(df)
A B C
species color
cat red 1 4 x
dog blue 2 5 y
bird yellow 3 6 z
如果先reset_index()
,您总是可以使用与引用列相同的方式引用索引的级别
抓取列'A'
df.reset_index()['A']
0 1
1 2
2 3
Name: A, dtype: int64
df['A']
species color
cat red 1
dog blue 2
bird yellow 3
Name: A, dtype: int64
抓取'color'
而不使用重置索引()
使用reset\u index()
这不是没有缺点的。该索引对于列
'A'
df.reset_index()['A']
0 1
1 2
2 3
Name: A, dtype: int64
df['A']
species color
cat red 1
dog blue 2
bird yellow 3
Name: A, dtype: int64
自动将
'index'
与'A'
列的值对齐,这是它作为索引的全部要点。您能给出一个具体的示例吗?