【问题标题】:python - applying a mask to an array in a for looppython - 在for循环中将掩码应用于数组
【发布时间】:2018-08-23 12:25:03
【问题描述】:

我有这个代码:

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = (result['depth'] ==  v)
    values_v = [result[string][temp_v] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

我想在其中创建一个名为“this_v”的新dict,其键与原始字典result 相同,但值更少。

行:

values_v = [result[string][temp_v] for string in result.keys()]

报错

TypeError: 只有整数标量数组可以转换为标量索引

我不明白,因为我可以创建 ex = result[result.keys()[0]][temp_v] 就好了。它只是不允许我使用 for 循环执行此操作,以便我可以填充列表。

知道为什么它不起作用吗?

【问题讨论】:

  • 请记住,所有 dict 值都是列表,而不是 NumPy 数组。将它们转换为正确的 NumPy 数组可能会改变一些事情。
  • 只需为您的dict值添加np.array

标签: python numpy dictionary


【解决方案1】:

为了解决您的问题(查找和删除重复项),我鼓励您使用pandas。它是一个 Python 模块,让你的生活变得异常简单:

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]),\
         np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

# Here comes pandas!
import pandas as pd

# Converting your dictionary of lists into a beautiful dataframe
df = pd.DataFrame(result)

#>    data         depth dimension generation
# 0     [0, 0, 0]   1       1        1
# 1     [0, 0, 0]   1       2        1
# 2     [0, 0, 0]   1       3        1
# 3     [0, 0, 0]   2       1        2
# 4     [0, 0, 0]   2       2        2
# 5     [0, 0, 0]   2       3        2


# Dropping duplicates... in one single command!
df = df.drop_duplicates('depth')

#>    data         depth dimension generation
# 0     [0, 0, 0]   1       1        1
# 3     [0, 0, 0]   2       1        2

如果您希望以原始格式返回您的数据...您只需要一行代码!

df.to_dict('list')

#> {'data': [array([0, 0, 0]), array([0, 0, 0])],
#   'depth': [1, 2],
#   'dimension': [1, 1],
#   'generation': [1, 2]}

【讨论】:

  • 熊猫已经成为我的新宗教!
猜你喜欢
  • 1970-01-01
  • 2015-04-30
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多