我想使用布尔掩码索引Pandas数据帧,然后根据整数索引在过滤后的数据帧的子集中设置一个值,并将此值反映在数据帧中.也就是说,如果这对数据框架有所了解,我会很高兴.
例:
In [293]:
df = pd.DataFrame({'a': [0, 1, 2, 3, 4, 5, 6, 7],
'b': [5, 5, 2, 2, 5, 5, 2, 2],
'c': [0, 0, 0, 0, 0, 0, 0, 0]})
mask = (df['a'] < 7) & (df['b'] == 2)
df.loc[mask, 'c']
Out[293]:
2 0
3 0
6 0
Name: c, dtype: int64
Run Code Online (Sandbox Code Playgroud)
现在我想设置过滤后的数据帧中返回的前两个元素的值.链接iloc到loc上面的呼叫工作索引:
In [294]:
df.loc[mask, 'c'].iloc[0: 2]
Out[294]:
2 0
3 0
Name: c, dtype: int64
Run Code Online (Sandbox Code Playgroud)
但不要分配:
In [295]:
df.loc[mask, 'c'].iloc[0: 2] = 1
print(df)
a b c
0 0 5 0
1 1 5 0
2 2 2 0
3 3 2 0
4 4 5 0
5 5 5 0
6 6 2 0
7 7 2 0
Run Code Online (Sandbox Code Playgroud)
使赋值与切片(即= [1, 1])的长度相同也不起作用.有没有办法分配这些值?
怎么样。
ix = df.index[mask][:2]
df.loc[ix, 'c'] = 1
Run Code Online (Sandbox Code Playgroud)
与 EdChum 的想法相同,但按照评论中的建议更优雅。
编辑:必须要小心一点,因为它可能会通过非唯一索引给出不需要的结果,因为上面的任一标签可能会索引多行ix。如果索引不唯一,并且您只需要满足布尔键的前 2(或 n)行,那么使用.iloc整数索引会更安全,例如
ix = np.where(mask)[0][:2]
df.iloc[ix, 'c'] = 1
Run Code Online (Sandbox Code Playgroud)
这确实有效但有点难看,基本上我们使用从掩码生成的索引并进行额外的调用loc:
In [57]:
df.loc[df.loc[mask,'c'].iloc[0:2].index, 'c'] = 1
df
Out[57]:
a b c
0 0 5 0
1 1 5 0
2 2 2 1
3 3 2 1
4 4 5 0
5 5 5 0
6 6 2 0
7 7 2 0
Run Code Online (Sandbox Code Playgroud)
所以突破以上:
In [60]:
# take the index from the mask and iloc
df.loc[mask, 'c'].iloc[0: 2]
Out[60]:
2 0
3 0
Name: c, dtype: int64
In [61]:
# call loc using this index, we can now use this to select column 'c' and set the value
df.loc[df.loc[mask,'c'].iloc[0:2].index]
Out[61]:
a b c
2 2 2 0
3 3 2 0
Run Code Online (Sandbox Code Playgroud)