Python:SQL计数/数字选项卡的等效功能

2024-06-23 19:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个有趣的技术,如果可能的话,我想找到一个类似的方法来测试:

SQL Server: Create New Records from Enumerated Date

select s.id
    , DATEADD(day, t.N - 1, s.transaction_dt)
    , s.measures
from @Something s
join cteTally t on t.N <= s.units
order by s.id
    , s.transaction_dt
    , t.N

作为一个基于集合的解决方案,这看起来非常有趣。我的问题是是否有可能在大熊猫身上复制类似的东西?地址:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html


Tags: 方法fromidpandasnewsqldateserver
1条回答
网友
1楼 · 发布于 2024-06-23 19:39:42

当然,有可能。我以您引用的SQL示例为例:

import pandas as pd

df = pd.DataFrame([[1, '2018-01-01', 4, 30.5],
                   [1, '2018-01-03', 4, 26.3],
                   [2, '2018-01-01', 3, 12.7],
                   [2, '2018-01-03', 3, 8.8]],
                  columns=['id', 'transaction_dt', 'units', 'measures'])

df_out = pd.DataFrame([df.iloc[idx] for idx in df.index \
                       for _ in range(df.iloc[idx]['units'])])

#    id transaction_dt  units  measures
# 0   1     2018-01-01      4      30.5
# 0   1     2018-01-01      4      30.5
# 0   1     2018-01-01      4      30.5
# 0   1     2018-01-01      4      30.5
# 1   1     2018-01-03      4      26.3
# 1   1     2018-01-03      4      26.3
# 1   1     2018-01-03      4      26.3
# 1   1     2018-01-03      4      26.3
# 2   2     2018-01-01      3      12.7
# 2   2     2018-01-01      3      12.7
# 2   2     2018-01-01      3      12.7
# 3   2     2018-01-03      3       8.8
# 3   2     2018-01-03      3       8.8
# 3   2     2018-01-03      3       8.8

相关问题 更多 >

    热门问题