我必须将每一列存储在数据框中(8 个五分位数)
i have to bucket each column in a dataframe (8 quintile)
我有一个包含 4 列的数据框,对于每一列,我们必须进行分桶(将数据分布在 8 个桶中),以便在不指定的情况下迭代地对第一列和第二列进行分桶,依此类推手动列名
这是我正在尝试的代码
for col in df3.columns[0:]:
cb1 = np.linspace(min(col), max(col), 11)
df3.insert(2 ,'buckets',pd.cut(col, cb1, labels=np.arange(1, 11, 1)))
print(df3[col])
这里df3是样本数据集
苹果橙香蕉
5 2 6
6 4 6
2 8 9
4 7 0
预期输出是
苹果橙香蕉bucket_applebucket_orangebucket_banana
5 2 6 1 3 2
6 4 6 1 1 4
2 8 9 2 1 8
4 7 0 5 4 1
这里的 bucket 列指定了与数据相关的 bucket 编号
由于输出是完全随机的,您的数据列和桶编号之间没有相关性,在这种情况下您应该单独生成桶。
for c in df.columns:
df['bucket_' + c] = np.random.randint(8, size=(len(df))) + 1
df # your random bucket df.
如果您希望桶大小相等:
for c in df.columns:
arr = np.arange(8) + 1
arr = np.repeat(arr, int(len(df))/8) # your df has to be divisible by 8
np.random.shuffle(arr) # shuffle the array.
df['bucket_' + c] = arr
我有一个包含 4 列的数据框,对于每一列,我们必须进行分桶(将数据分布在 8 个桶中),以便在不指定的情况下迭代地对第一列和第二列进行分桶,依此类推手动列名
这是我正在尝试的代码
for col in df3.columns[0:]:
cb1 = np.linspace(min(col), max(col), 11)
df3.insert(2 ,'buckets',pd.cut(col, cb1, labels=np.arange(1, 11, 1)))
print(df3[col])
这里df3是样本数据集
苹果橙香蕉
5 2 6
6 4 6
2 8 9
4 7 0
预期输出是
苹果橙香蕉bucket_applebucket_orangebucket_banana
5 2 6 1 3 2
6 4 6 1 1 4
2 8 9 2 1 8
4 7 0 5 4 1
这里的 bucket 列指定了与数据相关的 bucket 编号
由于输出是完全随机的,您的数据列和桶编号之间没有相关性,在这种情况下您应该单独生成桶。
for c in df.columns:
df['bucket_' + c] = np.random.randint(8, size=(len(df))) + 1
df # your random bucket df.
如果您希望桶大小相等:
for c in df.columns:
arr = np.arange(8) + 1
arr = np.repeat(arr, int(len(df))/8) # your df has to be divisible by 8
np.random.shuffle(arr) # shuffle the array.
df['bucket_' + c] = arr