在 pandas Dataframe 的任意切片中以 Python 方式递增数字

标签 python pandas

这段代码显示了我想要创建的 DataFrame

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

结果如下:

    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

我想找出一种方法,可以在系列的任意切片上创建这些 1,2,...,n 系列。即:df['2012-04-05':'2012-04-07'] = magic_function()

但我不确定如何在不使用循环的情况下做到这一点。

最佳答案

IIUC,您可以使用 loc 进行切片并分配一个 range

df['what_i_want'] = 0
df.loc['2012-04-05':'2012-04-07', 'what_i_want'] = range(1, 4)

df

            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 Dataframe 的任意切片中以 Python 方式递增数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48458813/

相关文章:

python - 从字符串 NLP 中删除英语 "crap"单词的策略,例如 "um"、 "uh"

python - 实验中的导出策略是什么?

python - 如何在 mac os x (10.9) 上的 python 中安装 libgpuarray 和 clBLAS?

python - 使用 Python 在混合列中将 GB 复杂转换为 TB

python - R Lattice 类似于 Python、Pandas 和 Matplotlib 的绘图

python - Pandas `isin` 函数的更快替代方案

python - Python 中多维矩阵(数组)的乘法

python - OSError : [Errno 36] File name too long: for python package and . txt 文件, Pandas 打开

python - 计数为 aggfunc 的数据透视表给出与 value_counts 不同的结果

python - 使用 df.to_sql() 将 block 写入数据库时​​出现 Pandas 错误