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

如何生成[1,1,2,2,…,n,n]序列并添加至DataFrame列?

Solution

1. Generate the Repeated Sequence

Use this one-line list comprehension to create the sequence [1, 1, 2, 2, …, n, n] for any integer n:

sequence = [num for num in range(1, n+1) for _ in range(2)]

This works by iterating over each number from 1 to n, and appending each number twice via the inner loop.

2. Add Sequence to a Pandas DataFrame

First import pandas, then assign the generated sequence to a new column in your DataFrame. Example:

import pandas as pd

# Replace with your actual DataFrame
df = pd.DataFrame({'existing_col': [10, 20, 30, 40, 50, 60]})

# Set n to half the row count (since each number repeats twice)
n = len(df) // 2
sequence = [num for num in range(1, n+1) for _ in range(2)]

# Add the sequence as a new column
df['repeated_seq'] = sequence

If your DataFrame has an odd number of rows, adjust n or pad the sequence to match the row count as needed.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:21:48