如何生成[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
相关产品推荐
相关产品推荐

