在 pandas 中使用.loc和MultiIndex? [英] Using .loc with a MultiIndex in pandas?
问题描述
有人知道是否可以使用DataFrame.loc方法从MultiIndex中进行选择吗?我有以下DataFrame,并且希望能够访问位于('at', 1)
,('at', 3)
,('at', 5)
等(非顺序)的索引的驻留"列中的值.>
我很希望能够做类似data.loc[['at',[1,3,5]], 'Dwell']
的事情,类似于常规索引的data.loc[[1,3,5], 'Dwell']
语法(该索引返回一个由3个成员组成的Dwell值系列).
我的目的是选择数据的任意子集,仅对该子集执行一些分析,然后使用分析结果更新新值.我计划使用相同的语法为这些数据设置新值,因此在这种情况下,链接选择器实际上将不起作用.
以下是我正在使用的DataFrame的一部分:
Char Dwell Flight ND_Offset Offset
QGram
at 0 a 100 120 0.000000 0
1 t 180 0 0.108363 5
2 a 100 120 0.000000 0
3 t 180 0 0.108363 5
4 a 20 180 0.000000 0
5 t 80 120 0.108363 5
6 a 20 180 0.000000 0
7 t 80 120 0.108363 5
8 a 20 180 0.000000 0
9 t 80 120 0.108363 5
10 a 120 180 0.000000 0
谢谢!
如果您使用的是0.14版本,则可以将元组简单地传递给.loc
,如下所示:
df.loc[('at', [1,3,4]), 'Dwell']
Does anyone know if it is possible to use the DataFrame.loc method to select from a MultiIndex? I have the following DataFrame and would like to be able to access the values located in the 'Dwell' columns, at the indices of ('at', 1)
, ('at', 3)
, ('at', 5)
, and so on (non-sequential).
I'd love to be able to do something like data.loc[['at',[1,3,5]], 'Dwell']
, similar to the data.loc[[1,3,5], 'Dwell']
syntax for a regular index (which returns a 3-member series of Dwell values).
My purpose is to select an arbitrary subset of the data, perform some analysis only on that subset, and then update the new values with the results of the analysis. I plan on using the same syntax to set new values for these data, so chaining selectors wouldn't really work in this case.
Here is a slice of the DataFrame I'm working with:
Char Dwell Flight ND_Offset Offset
QGram
at 0 a 100 120 0.000000 0
1 t 180 0 0.108363 5
2 a 100 120 0.000000 0
3 t 180 0 0.108363 5
4 a 20 180 0.000000 0
5 t 80 120 0.108363 5
6 a 20 180 0.000000 0
7 t 80 120 0.108363 5
8 a 20 180 0.000000 0
9 t 80 120 0.108363 5
10 a 120 180 0.000000 0
Thanks!
If you are on version 0.14, you can simply pass a tuple to .loc
as below:
df.loc[('at', [1,3,4]), 'Dwell']
这篇关于在 pandas 中使用.loc和MultiIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!