根据索引列表在循环中选择数据框的行

发布于 2025-02-12 01:27:47 字数 435 浏览 1 评论 0原文

我有一个数据框架&索引的两个(或多个)列表:

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)

idx1= [0,2,4]
idx2=[1,3,5]
idx3 =[...,...,..]

我想创建一个循环,可以在其中选择data的行。对于每次迭代,我使用一个列表。 因此,对于第一迭代,数据的行中显示了idx1 0,2,4中的行。

我该怎么做?

这是一个简化的示例,在我的实际代码中,我需要循环使用不同的功能。对于每个迭代都有不同的行。因此,对我来说,在循环中这样做很重要。

I have one data frame & two (or multiple) lists of indexes:

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)

idx1= [0,2,4]
idx2=[1,3,5]
idx3 =[...,...,..]

I want to create a loop where I can select the rows of data. for each iteration, I use one list.
so for 1st iteration data has the rows shown in idx1 0,2,4.

how I can do that ?

This is a simplified example, in my actual code, there are different functions that I need to loop on. for each iteration having different rows. Therefore it's important for me to do that within a loop.

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

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

发布评论

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

评论(1

从来不烧饼 2025-02-19 01:27:47

您可以使用data.loc [行]选择行。

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)
idx1 = [0,2,4]
idx2 = [1,3,5]

for r in (idx1, idx2):
    print(data.loc[r])

输出:

   Number_a  Number_b  Number_c
0        12        11        10
2        14        11         4
4        16        12         2
   Number_a  Number_b  Number_c
1        13        11         5
3        15        12         3
5        17        12         1

You can select rows with data.loc[rows].

data_ = {'Number_a': [12, 13, 14,15,16,17],'Number_b':[11,11,11,12,12,12],'Number_c': [10,5,4,3,2,1]}

data = pd.DataFrame(data=data_)
idx1 = [0,2,4]
idx2 = [1,3,5]

for r in (idx1, idx2):
    print(data.loc[r])

Output:

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