Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PostgreSQL:如何根据阈值将文本字符串拆分为多个片段?_Python_Sql_Postgresql - Fatal编程技术网

Python PostgreSQL:如何根据阈值将文本字符串拆分为多个片段?

Python PostgreSQL:如何根据阈值将文本字符串拆分为多个片段?,python,sql,postgresql,Python,Sql,Postgresql,我的PostgreSQL数据库中有一个示例数据,如下所示: ID Thresh array (int) (int) (text) 1 171 61,201,20.0 2 89 59,119,9.0 数组检查如下:在61、201、20.0中,第一个61和第二个201是数组范围的开始值和结束值。而,20.0是数组的平均值。对于每个ID,如果遇到阈值Thresh,我需要将数组范围分割成片。如果它没有遇到阈值,那么输

我的PostgreSQL数据库中有一个示例数据,如下所示:

ID       Thresh    array
(int)    (int)     (text)
1        171       61,201,20.0
2        89        59,119,9.0
数组检查如下:在
61、201、20.0
中,第一个
61
和第二个
201
数组
范围的
开始值和结束值。而,
20.0
数组的
平均值。对于每个
ID
,如果遇到阈值
Thresh
,我需要将
数组范围
分割成片。如果它没有遇到阈值,那么输出将是相同的。预期产出如下:

ID       Thresh    array
(int)    (int)     (text)
1        171       61,171,20.0,171,201,20.0
2        89        59,89,9.0,89,119,9.0

而拆分
数组
时,平均值(例如
20.0
9.0
将保持不变。有人能建议我如何将数组范围拆分为多个片段吗?

将字符串转换为数组,修改其元素(如有必要)并将数组转换回字符串:

with my_table(id, thresh, arr) as (
values
(1, 171, '61,201,20.0'),
(2, 89, '59,119,9.0')
)

select
    id, thresh,
    array_to_string(a, ',') as arr
from (
    select 
        id, thresh, 
        case 
            when thresh between a[1] and a[2] 
            then array[a[1], thresh, a[3], thresh, a[2], a[3]] 
            else a
        end as a
    from (
        select 
            id, thresh, 
            string_to_array(arr, ',')::float[] a
        from my_table
        ) s
    ) s;

 id | thresh |         arr          
----+--------+----------------------
  1 |    171 | 61,171,20,171,201,20
  2 |     89 | 59,89,9,89,119,9
(2 rows)

将字符串转换为数组,修改其元素(如有必要)并将数组转换回字符串:

with my_table(id, thresh, arr) as (
values
(1, 171, '61,201,20.0'),
(2, 89, '59,119,9.0')
)

select
    id, thresh,
    array_to_string(a, ',') as arr
from (
    select 
        id, thresh, 
        case 
            when thresh between a[1] and a[2] 
            then array[a[1], thresh, a[3], thresh, a[2], a[3]] 
            else a
        end as a
    from (
        select 
            id, thresh, 
            string_to_array(arr, ',')::float[] a
        from my_table
        ) s
    ) s;

 id | thresh |         arr          
----+--------+----------------------
  1 |    171 | 61,171,20,171,201,20
  2 |     89 | 59,89,9,89,119,9
(2 rows)

请向我们展示您迄今为止尝试的代码。这可能比你的英语解释更清楚。此外,如果可以查询数据库、处理文本和报告结果,请为
python
或类似内容添加标记。仅将解决方案约束为SQL可能比您希望的更为严格。谢谢您的建议。我已经编辑了标签。请给我们看看你迄今为止尝试过的代码。这可能比你的英语解释更清楚。此外,如果可以查询数据库、处理文本和报告结果,请为
python
或类似内容添加标记。仅将解决方案约束为SQL可能比您希望的更为严格。谢谢您的建议。我已经编辑了标签。