Python 将多列的值添加到一个集合()

Python adding values from multiple columns to a set()

我无法将 10 列的多个值合并为一个 set。我想使用一个集合,因为每一列都有重复的值,我希望获得所有值(医疗代码)的列表,而不重复列表中的任何值。我能够从第一列中进行初始设置,但是当我尝试添加其他列时,我得到一个 "unhashable type error".

这是我的代码:

data_sorted = data.fillna(0).sort_values(['PAT_ID', 'VISIT_NO'])
set_ICD1 = set(data_sorted['ICD_1'].unique())
print(len(set_ICD1))
set_ICD = set_ICD1.add(data_sorted['ICD_2'])

print(len(set_ICD))

这是我遇到的错误:

11586 # (not part of the error this is the length of the initial set)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-e3966ec54661> in <module>()
  1 set_ICD1 = set(data_sorted['ICD_1'].unique())
  2 print(len(set_ICD1))
----> 3 set_ICD = set_ICD1.add(data_sorted['ICD_2'].unique())
  4 
  5 print(len(set_ICD))

TypeError: unhashable type: 'numpy.ndarray'

如有任何解决此问题的建议或提示,我们将不胜感激!

如果您想一次向 set 添加多个元素,您需要使用 update method instead of add:

set_ICD1.update(data_sorted['ICD_2'])

如果它是一个 NumPy 数组,你可能应该使用 ravel()(如果它是 n 维的——这会使它变平)和 tolist()(为了性能):

set_ICD1.update(data_sorted['ICD_2'].ravel().tolist())