对于具有多级索引的数据帧,我遇到了 .loc 的行为,我无法解释。
设置:
import pandas as pd
df = pd.DataFrame({'ID': [1, 2, 3, 4],
'DT': [2018, 2018, 2017, 2018],
'F1': [0, 1, 0, 0],
'F2': [0, 0, 1, 0] })
df.loc[5]= [5, 2019, 1, 0]
df
到目前为止,一切都很好,看起来像(注意插入了索引为 5 的行):
ID DT F1 F2
0 1 2018 0 0
1 2 2018 1 0
2 3 2017 0 1
3 4 2018 0 0
5 5 2019 1 0
现在在“ID”和“DT”上创建一个具有多级索引的副本,并将其与 loc 一起使用:
indexed= df.set_index(['ID', 'DT'], inplace=False)
indexed.loc[(2, 2018)]
这仍然有效并输出对应于给定索引值的值:
F1 1
F2 0
Name: (2, 2018), dtype: int64
它也可以使用以下方式更新:
indexed.loc[(2, 2018)]= [1, 4]
现在尝试插入一个新行,就像我们在单级索引上所做的一样:
indexed.loc[(1, 2019)]= [3, 4]
这引发了一个异常:
ValueError: cannot set using a multi-index selection indexer with a different length than the value
并且数据框已更改,就好像 loc 访问将 2019 解释为列名一样。所以数据框现在看起来像:
F1 F2 2019
ID DT
1 2018 0 0 NaN
2 2018 1 0 NaN
3 2017 0 1 NaN
4 2018 0 0 NaN
5 2019 1 0 NaN
谁能解释这种奇怪的行为,或者这是一个错误?
请您参考如下方法:
使用 : 获取所有新列或更新列,不使用 : 是快捷方式,不幸的是仅适用于更新:
indexed.loc[(2, 2018), :]= [1, 4]
indexed.loc[(1, 2019), :]= [3, 4]
print (indexed)
F1 F2
ID DT
1 2018 0.0 0.0
2 2018 1.0 4.0
3 2017 0.0 1.0
4 2018 0.0 0.0
5 2019 1.0 0.0
1 2019 3.0 4.0
