You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以Pythonic方式在Pandas DataFrame任意切片生成递增序列

解决方法:给指定切片生成连续整数序列

嘿,这个需求其实用Pandas自带的工具就能轻松实现,完全不用写循环~下面直接给你几种简洁的实现方式:

方法一:用range配合.loc索引器

先初始化你需要的DataFrame(先把what_i_want默认设为0):

import pandas as pd

df = pd.DataFrame(index=pd.date_range(start='4/1/2012', periods=10))
df['foo'] = 7
df['what_i_want'] = 0

然后定位目标日期切片,生成1到n的序列并赋值:

# 选中目标日期范围的切片
target_slice = df['2012-04-05':'2012-04-07']
# 生成从1开始的连续整数序列,长度和切片一致
df.loc[target_slice.index, 'what_i_want'] = range(1, len(target_slice) + 1)

方法二:用numpy.arange简化代码

如果你习惯用NumPy,也可以用np.arange来生成序列,代码更紧凑:

import numpy as np

# 直接定位切片并赋值
df.loc['2012-04-05':'2012-04-07', 'what_i_want'] = np.arange(1, len(df.loc['2012-04-05':'2012-04-07']) + 1)

封装成你想要的magic_function

如果想按照你设想的magic_function()方式调用,直接把逻辑封装成函数就行:

def magic_function(slice_obj):
    # 根据传入的切片长度生成1到n的序列
    return range(1, len(slice_obj) + 1)

# 调用方式和你预期的一致
df.loc['2012-04-05':'2012-04-07', 'what_i_want'] = magic_function(df.loc['2012-04-05':'2012-04-07'])

最终效果

运行后你会得到和预期完全一致的结果:

foo  what_i_want
2012-04-01    7            0
2012-04-02    7            0
2012-04-03    7            0
2012-04-04    7            0
2012-04-05    7            1
2012-04-06    7            2
2012-04-07    7            3
2012-04-08    7            0
2012-04-09    7            0
2012-04-10    7            0

原理很简单:Pandas的.loc索引器会自动对齐索引,而range/np.arange能根据切片的长度精准生成连续整数,整个过程完全不需要循环,效率还很高~

内容的提问来源于stack exchange,提问作者user3556757

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:31:14