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

如何基于Col2的频次值扩展目标DataFrame?

Solution for Expanding DataFrame Rows Based on Column Values

Here's a straightforward approach using pandas to achieve your desired row expansion:

import pandas as pd

# Original DataFrame
df = pd.DataFrame({
    'Col1': ['a', 'a', 'b', 'b'],
    'Col2': [2, 1, 4, 2],
    'Col3': [6, 3, 2, 3]
})

# Expand rows based on Col2 values
expanded_df = df.repeat(df['Col2'])[['Col1', 'Col3']].reset_index(drop=True)

print(expanded_df)

Output:

Col1  Col3
0    a     6
1    a     6
2    a     3
3    b     2
4    b     2
5    b     2
6    b     2
7    b     3
8    b     3

How it works:

  • df.repeat(df['Col2']): This method repeats each row in the DataFrame exactly the number of times specified in Col2 for that row. For example, the first row (with Col2=2) is duplicated twice, the second row (Col2=1) stays as a single row, etc.
  • [['Col1', 'Col3']]: We select only the columns needed in the final output, dropping Col2 since it's no longer required.
  • reset_index(drop=True): This resets the index of the expanded DataFrame to a clean sequential index (0,1,2,...) instead of retaining the original duplicated indices.

Alternative approach using index.repeat:
If you prefer working with indices directly, you can also use this equivalent method:

expanded_df = df.loc[df.index.repeat(df['Col2'])][['Col1', 'Col3']].reset_index(drop=True)

This works by repeating the row indices according to Col2 values, then using those repeated indices to slice the original DataFrame, followed by selecting the desired columns and resetting the index.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:52:50