gpt4 book ai didi

python - bool 值 `loc` 和后续 `iloc` 的 Pandas 索引

转载 作者:太空狗 更新时间:2023-10-29 21:31:21 25 4
gpt4 key购买 nike

我想使用 bool 掩码为 Pandas 数据框编制索引,然后根据整数索引在过滤数据框的子集中设置一个值,并将该值反射(reflect)在数据框中。也就是说,如果这适用于数据框的 View ,我会很高兴。

例子:

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

现在我想设置过滤数据框中返回的前两个元素的值。将 iloc 链接到上面的 loc 调用可以索引:

In [294]:

df.loc[mask, 'c'].iloc[0: 2]

Out[294]:

2 0
3 0
Name: c, dtype: int64

但不赋值:

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

使分配值与切片长度相同(即 = [1, 1])也不起作用。有没有办法分配这些值?

最佳答案

这确实有效,但有点难看,基本上我们使用从掩码生成的索引并额外调用 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

所以分解上面的内容:

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

关于python - bool 值 `loc` 和后续 `iloc` 的 Pandas 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29608183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com