如何通过ID选择数据框中的行信息 - python

我是python的新手。我有一个像这样的大数据框:

    ID  x   y
0   1   x1  y1
1   0   x2  y2
2   0   x3  y3
3   2   x4  y4
4   1   x5  y5
5   2   x6  y6

我想在像这样的数据帧中,在ID 1和ID 2之间使用(x; y)对:

    coordinates
0   (x1,y1), (x2,y2), (x3,y3), (x4,y4)
1   (x5,y5), (x6,y6)

我已经尝试过两次进行迭代,但是计算起来很长。我怎么能得到这个东西?

参考方案

一种想法是通过每个1起始值创建组,并为元组聚合自定义lambda函数:

df['new'] = (df['ID'] == 1).cumsum()
print (df)
   ID   x   y  new
0   1  x1  y1    1
1   0  x2  y2    1
2   0  x3  y3    1
3   2  x4  y4    1
4   1  x5  y5    2
5   2  x6  y6    2

df1 = (df.groupby('new')['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

没有新列的类似解决方案:

df1 = (df.groupby((df['ID'].rename('new') == 1).cumsum())['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

编辑:

print (df)
   ID   x   y
0   1  x1  y1
1   0  x2  y2
2   0  x3  y3
3   2  x4  y4
4   0  x7  y7
4   0  x8  y8
4   1  x5  y5
5   2  x6  y6

g = df['ID'].eq(1).cumsum()
s = df['ID'].shift().eq(2).cumsum()

df = df[s.groupby(g).transform('min').eq(s)]
print (df)
   ID   x   y
0   1  x1  y1
1   0  x2  y2
2   0  x3  y3
3   2  x4  y4
4   1  x5  y5
5   2  x6  y6

df1 = (df.groupby((df['ID'].rename('new') == 1).cumsum())['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码import json with open('johns.json', 'r') as q: l = q.read() data = json.loads(l) data['john'] = '{}' data['john']['use…