【问题标题】:How to oversample an array of n string elements into an array of m string elements如何将 n 个字符串元素的数组过采样到 m 个字符串元素的数组中
【发布时间】:2023-03-13 11:17:01
【问题描述】:

我想将 n 元素的数组过采样到 m 元素的数组中,例如 m > n。

例如让我们取 n=3

colors=['red','blue','green']

设置 m =7

我在找什么?

 oversampled_colors=['green','blue','red','red','blue','green','blue']

【问题讨论】:

  • 您应该提供任何尝试此操作的示例。无论如何,如果您只想在oversampled 中进行随机过采样,请使用for 循环并将range 设置为您的m 值,然后使用randint 来自random 模块从colors 中随机选择值。
  • 字符串如何工作(在我的例子中)。 randint 用于 int 值
  • 您的值是 stings,但它们的索引是整数,而这些是您使用的东西。
  • 啊,是的,我明白了,谢谢

标签: arrays python-3.x numpy random oversampling


【解决方案1】:
import random
def fun(colors,n,m):
  colors1=[]
  while(len(colors1)<n):
      colors1.append(colors[random.randint(0,m-1)])
  return colors1
colors=['red','blue','green']
oversampled_colors=fun(colors,7,len(colors))
print(oversampled_colors)

【讨论】:

  • 感谢您的回答。但这不是随机的。对于 m = 7,您只需按照相同的顺序红蓝绿,直到达到 7 种颜色
  • 这个@ericlardon 怎么样
  • 虽然此代码可以回答问题,但提供有关 如何 和 为什么 解决问题的附加上下文将提高​​答案的长期价值。
【解决方案2】:

np.random.choice 似乎就是你要找的东西

>>> colors=['red','blue','green']
>>> np.random.choice(colors, 7)
array(['red', 'red', 'green', 'red', 'blue', 'red', 'green'], dtype='<U5')

【讨论】:

  • random.choices(colors, k=7) - choice 只是一个
  • @PatrickArtner 您可能正在考虑random 模块。 numpy.random 相似但不同。特别是肯定是choice。 choices 不存在。
  • 天哪 - 感谢您指出这一点,您已经获得了 +1 :) 现在考虑 +2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 2017-03-12
  • 2012-10-02
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多