pandas - 可以在分层索引中使用 loc[] 的整数索引吗?
问题描述
我认为 .loc[] 只允许标签或布尔索引,但在这段代码中,整数索引用于分层索引系列中的 .loc[] (data.loc[:, 2]) 这仅在分层索引系列中才有可能/数据框还是因为在构造函数中指定了整数索引?
data = pd.Series(np.random.randn(9), index=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'], [1,2,3,1,3,1,2,2,3]])
a 1 -0.204708
2 0.478943
3 -0.519439
b 1 -0.555730
3 1.965781
c 1 1.393406
2 0.092908
d 2 0.281746
3 0.769023
data.loc[:, 2]
a 0.478943
c 0.092908
d 0.281746
dtype: float64
解决方案
从文档中引用:
Series.loc
Access a group of rows and columns by label(s) or a boolean array.
.loc[] is primarily label based, but may also be used with a boolean array.
Allowed inputs are:
A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
在您的示例中,2 被解释为索引标签而不是位置。您可以对非分层索引系列执行相同操作:
data = pd.Series(np.random.randn(9))
data.loc[2]
推荐阅读
- python - Pandas Dataframe 问题:应用函数添加带有结果的新列
- swift - 设置布局的理想场所
- python - 具有多个条件的 Groupby 函数
- android - I/HwPointEventFilter:不支持 AFT,因为没有配置
- flutter - 错误:“尝试创建未注册类型的平台视图:umair.mapbox_navigation/mapboxMapView”
- r - 如何检查列中的条目并在不正确时删除?
- javascript - Javascript Tic Tac Toe AI - 未选择最佳空间
- java - 改造在 API 中没有任何问题:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
- java - Talend Open Studio - java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 - tMap
- security - 便宜的单线程密码哈希算法