AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-4451315

ignoring_gravity's questions

Martin Hope
ignoring_gravity
Asked: 2025-03-03 22:03:52 +0800 CST

保留 list[struct] 列的字段包含消息的行

  • 7

假设我有以下数据:

import duckdb
rel = duckdb.sql("""
    FROM VALUES
        ([{'a': 'foo', 'b': 'bta'}]),
        ([]),
        ([{'a': 'jun', 'b': 'jul'}, {'a':'nov', 'b': 'obt'}])
        df(my_col)
    SELECT *
""")

看起来像这样:

┌──────────────────────────────────────────────┐
│                    my_col                    │
│        struct(a varchar, b varchar)[]        │
├──────────────────────────────────────────────┤
│ [{'a': foo, 'b': bta}]                       │
│ []                                           │
│ [{'a': jun, 'b': jul}, {'a': nov, 'b': obt}] │
└──────────────────────────────────────────────┘

我想保留所有行,其中元素之一中的任何项目'my_col',字段'a'包含子字符串'bt'

因此,预期输出:

┌──────────────────────────────────────────────┐
│                    my_col                    │
│        struct(a varchar, b varchar)[]        │
├──────────────────────────────────────────────┤
│ [{'a': foo, 'b': bta}]                       │
│ [{'a': jun, 'b': jul}, {'a': nov, 'b': obt}] │
└──────────────────────────────────────────────┘

我该如何编写 SQL 查询来执行此操作?

python
  • 1 个回答
  • 27 Views
Martin Hope
ignoring_gravity
Asked: 2025-01-09 18:07:38 +0800 CST

关于python:来自Python字典的DuckDBPyRelation?

  • 6

在 Polars / pandas / PyArrow 中,我可以从字典中实例化一个对象,例如

In [12]: pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
Out[12]:
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 4   │
│ 2   ┆ 5   │
│ 3   ┆ 6   │
└─────┴─────┘

有没有办法在 DuckDB 中做到这一点,而无需通过 pandas/pyarrow/等?

python
  • 1 个回答
  • 38 Views
Martin Hope
ignoring_gravity
Asked: 2024-12-29 03:09:13 +0800 CST

使用 DuckDB 关系 API 进行“n_unique”聚合

  • 7

说我有

import duckdb

rel = duckdb.sql('select * from values (1, 4), (1, 5), (2, 6) df(a, b)')
rel
Out[3]: 
┌───────┬───────┐
│   a   │   b   │
│ int32 │ int32 │
├───────┼───────┤
│     1 │     4 │
│     1 │     5 │
│     2 │     6 │
└───────┴───────┘

我可以按 a 分组并通过执行以下操作找到“b”的平均值:

rel.aggregate(
    [duckdb.FunctionExpression('mean', duckdb.ColumnExpression('b'))],
    group_expr='a',
)
┌─────────┐
│ mean(b) │
│ double  │
├─────────┤
│     4.5 │
│     6.0 │
└─────────┘

效果非常好

有没有类似的方法来创建“n_unique”聚合?我正在寻找类似的东西

rel.aggregate(
    [duckdb.FunctionExpression('count_distinct', duckdb.ColumnExpression('b'))],
    group_expr='a',
)

但那并不存在。有什么东西可以做到吗?

python
  • 1 个回答
  • 44 Views
Martin Hope
ignoring_gravity
Asked: 2024-11-11 02:55:19 +0800 CST

使用 DuckDB 的 Python 关系 API 进行滚动求和

  • 8

说我有

data = {'id': [1, 1, 1, 2, 2, 2],
 'd': [1, 2, 3, 1, 2, 3],
 'sales': [1, 4, 2, 3, 1, 2]}

我想计算一个滚动总和,窗口为 2,按 'id' 分区,按 'd' 排序

使用 SQL 我可以做到:

duckdb.sql("""
select *, sum(sales) over w as rolling_sales
from df
window w as (partition by id order by d rows between 1 preceding and current row)
""")
Out[21]:
┌───────┬───────┬───────┬───────────────┐
│  id   │   d   │ sales │ rolling_sales │
│ int64 │ int64 │ int64 │    int128     │
├───────┼───────┼───────┼───────────────┤
│     1 │     1 │     1 │             1 │
│     1 │     2 │     4 │             5 │
│     1 │     3 │     2 │             6 │
│     2 │     1 │     3 │             3 │
│     2 │     2 │     1 │             4 │
│     2 │     3 │     2 │             3 │
└───────┴───────┴───────┴───────────────┘

这很有效,但是我如何使用 Python 关系 API 来实现它呢?

我已经

rel = duckdb.sql('select * from df')
rel.sum(
    'sales',
    projected_columns='*',
    window_spec='over (partition by id order by d rows between 1 preceding and current row)'
)

由此得出

┌───────────────────────────────────────────────────────────────────────────────────────┐
│ sum(sales) OVER (PARTITION BY id ORDER BY d ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) │
│                                        int128                                         │
├───────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                     3 │
│                                                                                     4 │
│                                                                                     3 │
│                                                                                     1 │
│                                                                                     5 │
│                                                                                     6 │
└───────────────────────────────────────────────────────────────────────────────────────┘

这很接近,但不太正确 - 我如何获取最后一列的名称rolling_sales?

python
  • 1 个回答
  • 28 Views
Martin Hope
ignoring_gravity
Asked: 2024-10-21 23:38:33 +0800 CST

根据映射替换数组中的所有值

  • 5

假设我有:

import pyarrow as pa

arr = pa.array([1, 3, 2, 2, 1, 3])

我想根据{1: 'one', 2: 'two', 3: 'three'}并最终替换值:

<pyarrow.lib.LargeStringArray object at 0x7f8dd0b3c820>
[
  "one",
  "three",
  "two",
  "two",
  "one",
  "three"
]

我可以通过 Polars 来实现这一点:

In [19]: pl.from_arrow(arr).replace_strict({1: 'one', 2: 'two', 3: 'three'}, return_dtype=pl.String).to_arrow()
Out[19]:
<pyarrow.lib.LargeStringArray object at 0x7f8dd0b3c820>
[
  "one",
  "three",
  "two",
  "two",
  "one",
  "three"
]

有没有办法只用 PyArrow 来完成它?

python
  • 1 个回答
  • 33 Views
Martin Hope
ignoring_gravity
Asked: 2024-09-11 16:07:12 +0800 CST

pyarrow chunkedarray 获取给定索引处的项目

  • 5

说我有

In [3]: import pyarrow as pa

In [4]: ca = pa.chunked_array([[1,2,3], [4,5,6]])

我想提取元素[1, 4, 2]并最终得到

<pyarrow.lib.Int64Array object at 0x7f6eb43c2d40>
[
  2,
  5,
  3
]

就像我在做 NumPy 风格的索引一样

python
  • 1 个回答
  • 20 Views
Martin Hope
ignoring_gravity
Asked: 2024-09-05 21:17:09 +0800 CST

滚动平均值的最小周期

  • 9

假设我有:

data = {
    'id': ['a', 'a', 'a', 'b', 'b', 'b', 'b'],
    'd': [1,2,3,0,1,2,3],
    'sales': [5,1,3,4,1,2,3],
}

我想添加一个带有滚动平均值的列,窗口大小为 2 min_periods=2,'id'

在 Polars 中,我可以执行以下操作:

import polars as pl

df = pl.DataFrame(data)
df.with_columns(sales_rolling = pl.col('sales').rolling_mean(2).over('id'))
shape: (7, 4)
┌─────┬─────┬───────┬───────────────┐
│ id  ┆ d   ┆ sales ┆ sales_rolling │
│ --- ┆ --- ┆ ---   ┆ ---           │
│ str ┆ i64 ┆ i64   ┆ f64           │
╞═════╪═════╪═══════╪═══════════════╡
│ a   ┆ 1   ┆ 5     ┆ null          │
│ a   ┆ 2   ┆ 1     ┆ 3.0           │
│ a   ┆ 3   ┆ 3     ┆ 2.0           │
│ b   ┆ 0   ┆ 4     ┆ null          │
│ b   ┆ 1   ┆ 1     ┆ 2.5           │
│ b   ┆ 2   ┆ 2     ┆ 1.5           │
│ b   ┆ 3   ┆ 3     ┆ 2.5           │
└─────┴─────┴───────┴───────────────┘

DuckDB 的对应产品是什么?我试过

import duckdb

duckdb.sql("""
    select
        *,
        mean(sales) over (
            partition by id 
            order by d
            range between 1 preceding and 0 following
        ) as sales_rolling 
    from df
""").sort('id', 'd')

但得到

┌─────────┬───────┬───────┬───────────────┐
│   id    │   d   │ sales │ sales_rolling │
│ varchar │ int64 │ int64 │    double     │
├─────────┼───────┼───────┼───────────────┤
│ a       │     1 │     5 │           5.0 │
│ a       │     2 │     1 │           3.0 │
│ a       │     3 │     3 │           2.0 │
│ b       │     0 │     4 │           4.0 │
│ b       │     1 │     1 │           2.5 │
│ b       │     2 │     2 │           1.5 │
│ b       │     3 │     3 │           2.5 │
└─────────┴───────┴───────┴───────────────┘

这非常接近,但当窗口中只有一个值时,duckdb 仍会计算滚动平均值。我如何复制min_periods=2Polars 的(默认)行为?

python
  • 1 个回答
  • 48 Views
Martin Hope
ignoring_gravity
Asked: 2024-08-24 17:39:07 +0800 CST

如何将两个 PyArrow 数组压缩在一起?

  • 6

在极坐标中,我可以使用从掩码中或根据掩码zip_width获取值:s1s2

In [1]: import polars as pl

In [2]: import pyarrow as pa

In [3]: import pyarrow as pc

In [4]: s1 = pl.Series([1,2,3])

In [5]: mask = pl.Series([True, False, False])

In [6]: s2 = pl.Series([4, 5, 6])

In [7]: s1.zip_with(mask, s2)
Out[7]:
shape: (3,)
Series: '' [i64]
[
        1
        5
        6
]

我该如何使用 PyArrow 来实现这一点?我试过了,pyarrow.compute.replace_with_mask但效果不一样:

In [10]: import pyarrow.compute as pc

In [11]: import pyarrow as pa

In [12]: a1 = pa.array([1,2,3])

In [13]: mask = pa.array([True, False, False])

In [14]: a2 = pa.array([4,5,6])

In [15]: pc.replace_with_mask(a1, pc.invert(mask), a2)
Out[15]:
<pyarrow.lib.Int64Array object at 0x7f69d411afe0>
[
  1,
  4,
  5
]

如何zip_with在 PyArrow 中复制?

python
  • 1 个回答
  • 20 Views
Martin Hope
ignoring_gravity
Asked: 2024-07-15 18:05:17 +0800 CST

如何将字符串附加到分块数组的每个元素?

  • 5

说我有

In [22]: import pyarrow as pa

In [23]: t = pa.table({'a': ['one', 'two', 'three']})

我想'_frobenius'将'a'

预期输出:

pyarrow.Table
a: string
----
a: [["one_frobenius","two_frobenius","three_frobenius"]]
python
  • 2 个回答
  • 49 Views
Martin Hope
ignoring_gravity
Asked: 2024-03-16 15:45:23 +0800 CST

为什么 `.rename(columns={'b': 'b'}, copy=False)` 后跟 inplace 方法不更新原始数据帧?

  • 7

这是我的例子:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

In [3]: df1 = df.rename(columns={'b': 'b'}, copy=False)

In [4]: df1.isetitem(1, [7,8,9])

In [5]: df
Out[5]:
   a  b
0  1  4
1  2  5
2  3  6

In [6]: df1
Out[6]:
   a  b
0  1  7
1  2  8
2  3  9

如果df1是从dfwith派生的copy=False,那么我预计对 的就地修改df1也会影响df。但事实并非如此。为什么?

我正在使用 pandas 版本 2.2.1,未启用任何选项(例如写入时复制)

python
  • 2 个回答
  • 32 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve