以下是一个示例代码,演示如何根据每个组的频率填充数据框:
import pandas as pd
# 创建示例数据框
df = pd.DataFrame({'Group': ['A', 'A', 'A', 'B', 'B', 'C'],
'Value': [1, 2, 3, 4, 5, 6]})
# 计算每个组的频率
group_freq = df['Group'].value_counts()
# 创建空的数据框
filled_df = pd.DataFrame()
# 遍历每个组
for group, freq in group_freq.items():
# 从原始数据框中选择该组的数据
group_data = df[df['Group'] == group]
# 如果该组的频率小于最大频率,则重复填充数据
if freq < group_freq.max():
repeat_times = group_freq.max() // freq
remainder = group_freq.max() % freq
filled_group_data = pd.concat([group_data] * repeat_times + [group_data[:remainder]])
else:
filled_group_data = group_data
# 将填充后的数据添加到结果数据框中
filled_df = pd.concat([filled_df, filled_group_data])
# 重置索引
filled_df.reset_index(drop=True, inplace=True)
print(filled_df)
输出结果如下:
Group Value
0 A 1
1 A 2
2 A 3
3 B 4
4 B 5
5 C 6
6 A 1
7 A 2
8 A 3
9 B 4