[英]Setting values of multiindex dataframe using only one-level indexing
My question is a logical continuation of this topic: Setting values with multiindex in pandas .我的问题是本主题的逻辑延续: Setting values with multiindex in pandas 。 So the example and answer from this, suits my situation either.
所以这个例子和答案也适合我的情况。
They set a multiindex value with f.loc[(slice(None), "one"), 0] = 1
他们使用
f.loc[(slice(None), "one"), 0] = 1
设置多f.loc[(slice(None), "one"), 0] = 1
值
But in my case, i have lot's of dataframes with custom number of index levels , so i would like to use indexing only on last level, without specifying others - smth like f.loc[:::, "one"), 0] = 1
.但在我的情况下,我有很多具有自定义索引级别数的数据帧,所以我只想在最后一级使用索引,而不指定其他 - 像
f.loc[:::, "one"), 0] = 1
。 PS Also, if i have an Indexer
for column "one", am i able to use it? PS另外,如果我有一个列“一”的
Indexer
,我可以使用它吗? Indexer can be an array: array([ True, True, True, ..., True, True, True], dtype=bool)
索引器可以是一个数组:
array([ True, True, True, ..., True, True, True], dtype=bool)
IIUC you want to use pd.IndexSlice
: IIUC 你想使用
pd.IndexSlice
:
In [276]: df
Out[276]:
0 1
first second
bar one 0.414213 -0.316333
two 1.109279 0.307283
baz one -0.287986 -1.963492
two 0.858867 0.553895
foo one -0.152813 -2.489409
two 1.022960 0.377656
qux one 1.549389 -0.307250
two -1.150914 -3.517356
In [277]: df.loc[pd.IndexSlice[:,'one'], 0] = 1
In [278]: df
Out[278]:
0 1
first second
bar one 1.000000 -0.316333
two 1.109279 0.307283
baz one 1.000000 -1.963492
two 0.858867 0.553895
foo one 1.000000 -2.489409
two 1.022960 0.377656
qux one 1.000000 -0.307250
two -1.150914 -3.517356
boolean indexing using mask
:使用
mask
布尔索引:
In [291]: mask = (df[0] > 1).values
In [292]: mask
Out[292]: array([False, True, False, False, False, True, False, False], dtype=bool)
In [293]: df.loc[mask]
Out[293]:
0 1
first second
bar two 1.109279 0.307283
foo two 1.022960 0.377656
In [294]: df.iloc[mask]
Out[294]:
0 1
first second
bar two 1.109279 0.307283
foo two 1.022960 0.377656
In [295]: df[mask]
Out[295]:
0 1
first second
bar two 1.109279 0.307283
foo two 1.022960 0.377656
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.