且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每个 id 创建 n 行 | pandas

更新时间:2023-12-04 13:36:52

这是一个使用 Counter 计算每个 ID 需要多少额外行,然后追加新数据的解决方案:

Here's a solution using Counter to count how many extra rows you need for each ID, and then just appending the new data:

from collections import Counter
id_count = Counter(df['id'])
# Create lists of each id repeated the number of times each is needed:
n = 4
id_values = [[i] * (n - id_count[i]) for i in id_count.keys()]
# Flatten to a single list:
id_values = [i for s in id_values for i in s]
# Create as new DataFrame and append to existing data:
new_data = pd.DataFrame({"id": id_values})
df = df.append(new_data).sort_values(by="id")