【问题标题】:Replace numpy 2D array numbers according numbers in df columns根据 df 列中的数字替换 numpy 2D 数组编号
【发布时间】:2019-03-24 10:56:13
【问题描述】:

我有一个带有一些数字的 2D numpy 数组,还有一个带有两列的 df。我需要根据 df 中的旧/新标签对替换 2D 数组中的所有数字。我该怎么做?

np.random.randint(15, size = (2,100))
df = pd.DataFrame({ 'old labels' : range(0,15 ,1),
    'new labels' : random.sample(range(0,15), 15)})

【问题讨论】:

标签: python arrays pandas numpy


【解决方案1】:

这将起作用,给定

arr = np.random.randint(15, size = (2,100))
df = pd.DataFrame({ 'old labels' : range(0,15 ,1),
    'new labels' : random.sample(range(0,15), 15)})

假设我们只有两个维度。

d = df['new labels'].to_dict()
arr = np.array([d[x] for y in arr.tolist() for x in y]).reshape(arr.shape)

【讨论】:

    【解决方案2】:

    这只是一个映射。使用 numpy 技巧和效率:

    data= np.random.randint(15, size = (2,100))
    map= df['new labels'].values
    result = map[data]
    

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多