【发布时间】:2022-01-20 11:57:09
【问题描述】:
我在 pandas 中有一个数据框,我需要将其分组并存储在一个新数组中,我需要每个组的大小具有特定大小,如果一个超过最小大小,则应将其添加到之前的组之一尺寸最小的。例如,在对数据进行分组后,我将拥有 G 组,即 len(G)<=b、len(G)>=a 或 a <= len(G) <= b。所以,我需要用len(G)>=a 使组满足a <= len(G) <= b 的条件。
代码正在运行。所以,我想知道是否有更方便的方法来做到这一点。
import numpy as np
import pandas as pd
rng = np.random.default_rng() # Just for testing
df = pd.DataFrame(rng.integers(0, 10, size=(1000, 4)), columns=list('ABCD'))
# The dataframe is grouped depend on specific column.
ans = [pd.DataFrame(y) for x, y in df.groupby(df.columns[3], as_index=False)]
n = 20 # The maximum size of the group is 25
new_arrayi_index = 0
new_array = []
for count_index in range(len(ans)):
l = ans[count_index]
if len(l) > n:
df_shuffled = pd.DataFrame(l).sample(frac=1)
final = [df_shuffled[i:i+n] for i in range(0,df_shuffled.shape[0],n)]
for inde in range(len(final)):
if len(final[inde]) <= 5 and new_arrayi_index != 0: #The minimum size of the group is 5
new_array[new_arrayi_index - 1]=new_array[new_arrayi_index - 1]+final[inde]
else:
new_array.append(final[inde])
new_arrayi_index += 1
else:
new_array.append(l)
new_arrayi_index += 1
count_index_ = 0
for count_index in range(len(new_array)):
print("count", count_index, "Size", len(new_array[count_index]))
print(new_array[count_index])
count_index_ += count_index
print(count_index_)
【问题讨论】:
-
您能否提供一些最小示例数据和其余变量(例如
ans),以便我们仅使用问题中的信息运行您的代码?我可以立即发现一些东西(例如len(l)//n),但要正确重构它,我需要能够先运行它。 -
我已经添加了 cmets 来解释这些变量。
-
您的标题表明您需要大小为
a <= len(l) <= b的样本,为此您可以删除项目或重复项目。这是正确的吗? -
我想要一个大小为
a <= len(l) <= b的样本,但如果该组不能满足条件,我必须将其添加到最小的组中。重复的项目可以在那里。假设我有 3 组 20 个元素,最后一组是一个。所以,我应该把那个加到 20 中。 -
所以,您想将数据拆分为一个暗淡列表
N x num_cols,这里的 N 为 20。理想情况下,您希望new_array中的所有条目的大小为 20,并且单个条目可能更小(但如果它小于最小值,则应该略大于 20)对吗?各个条目的顺序重要吗?