当我有一个多索引列时,如何使用.loc?

2024-03-29 11:58:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一段简短的代码来说明什么让我困惑:

import numpy as np
import pandas as pd

a = [0.2,0.4]
f = np.linspace(0.0,4.0,5)

mindex = pd.MultiIndex.from_product([a,f], names=['a', 'f'])
df = pd.DataFrame(dtype=float, index=range(0,100), columns=mindex)

有关数据帧的打印结构,请参阅编辑。现在,我想知道如何具体地使用.loc为特定元素赋值。显然,以下是:

print(df.loc[0, 0.2, 0.0])

给我一个错误:

pandas.core.indexing.IndexingError: Too many indexers

但我不明白为什么?以下两个语句按预期工作:

print(df.loc[0])
print(df.loc[0,0.2])

print(df.loc[0,0.2])为例输出:

f
0.0   NaN
1.0   NaN
2.0   NaN
3.0   NaN
4.0   NaN
Name: 0, dtype: float64

但是如何得到最终的f=0.0值呢?你知道吗

另外,我的下一个想法是使用元组作为列索引,但是print(df.loc[0,[0.2,0.0]])也不起作用。你知道吗


编辑:只是为了澄清我的数据帧的结构。你知道吗

print(df)

提供:

a  0.2                 0.4                
f  0.0 1.0 2.0 3.0 4.0 0.0 1.0 2.0 3.0 4.0
0  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
...
...

编辑2:为了在评论之后更新,基本上有两个建议是使用df.loc[0][0.2][0.0]df[[(0.2,0.0)]].loc[0]。然而,由于我需要它来为特定元素赋值,这两种方法似乎都被pandas所阻止(参见http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy)。你知道吗

实际上,df.loc[0][0.2][0.0] = 2似乎可以工作,但df[[(0.2,0.0)]].loc[0] = 2不行(因为它返回的是切片的副本而不是视图)。你知道吗


Tags: 数据import元素编辑pandasdfasnp