搜索和选择python pandas的小区周围的区域

发布于 2025-02-07 15:44:33 字数 86 浏览 3 评论 0原文

我最近一直在使用熊猫来工作,我是新手。我有一个数据框架,我想搜索整个数据框架上的特定字符串,然后在其右侧和左侧选择 n 单元格。我该怎么做?

I have been using pandas for work lately and I am fairly new to it. I have a data frame and I wanted to search the whole data frame for a specific string and then select the n cells to the right and to the left of it. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小ぇ时光︴ 2025-02-14 15:44:33

假设此虚拟输入,我们将寻找0作为目标,n = 2在左/右的值:

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 10, size=[10,10]))

   0  1  2  3  4  5  6  7  8  9
0  5  0  3  3  7  9  3  5  2  4
1  7  6  8  8  1  6  7  7  8  1
2  5  9  8  9  4  3  0  3  5  0
3  2  3  8  1  3  3  3  7  0  1
4  9  9  0  4  7  3  2  7  2  0
5  0  4  5  5  6  8  4  1  4  9
6  8  1  1  7  9  9  3  6  7  2
7  0  3  5  9  4  4  6  4  4  3
8  4  4  8  4  3  7  5  5  0  1
9  5  9  3  0  5  0  1  2  4  2

处理:输出:

n = 2

# get target as mask
mask = df.eq(0)

#generate a mask
mask2 = mask.astype(int).rolling(2*n+1, min_periods=1, center=True, axis=1).sum().gt(0)

# select cells
# here it's unclear what you want to do
# so as example let's mask the non-match cells
df.where(mask2, '-')

输出:

   0  1  2  3  4  5  6  7  8  9
0  5  0  3  3  -  -  -  -  -  -
1  -  -  -  -  -  -  -  -  -  -
2  -  -  -  -  4  3  0  3  5  0
3  -  -  -  -  -  -  3  7  0  1
4  9  9  0  4  7  -  -  7  2  0
5  0  4  5  -  -  -  -  -  -  -
6  -  -  -  -  -  -  -  -  -  -
7  0  3  5  -  -  -  -  -  -  -
8  -  -  -  -  -  -  5  5  0  1
9  -  9  3  0  5  0  1  2  -  -

Assuming this dummy input, we'll be looking for 0 as target with n=2 values on the left/right:

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 10, size=[10,10]))

   0  1  2  3  4  5  6  7  8  9
0  5  0  3  3  7  9  3  5  2  4
1  7  6  8  8  1  6  7  7  8  1
2  5  9  8  9  4  3  0  3  5  0
3  2  3  8  1  3  3  3  7  0  1
4  9  9  0  4  7  3  2  7  2  0
5  0  4  5  5  6  8  4  1  4  9
6  8  1  1  7  9  9  3  6  7  2
7  0  3  5  9  4  4  6  4  4  3
8  4  4  8  4  3  7  5  5  0  1
9  5  9  3  0  5  0  1  2  4  2

processing:

n = 2

# get target as mask
mask = df.eq(0)

#generate a mask
mask2 = mask.astype(int).rolling(2*n+1, min_periods=1, center=True, axis=1).sum().gt(0)

# select cells
# here it's unclear what you want to do
# so as example let's mask the non-match cells
df.where(mask2, '-')

output:

   0  1  2  3  4  5  6  7  8  9
0  5  0  3  3  -  -  -  -  -  -
1  -  -  -  -  -  -  -  -  -  -
2  -  -  -  -  4  3  0  3  5  0
3  -  -  -  -  -  -  3  7  0  1
4  9  9  0  4  7  -  -  7  2  0
5  0  4  5  -  -  -  -  -  -  -
6  -  -  -  -  -  -  -  -  -  -
7  0  3  5  -  -  -  -  -  -  -
8  -  -  -  -  -  -  5  5  0  1
9  -  9  3  0  5  0  1  2  -  -
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文