python - 通过 HashMap 根据其他列设置或替换数据帧列中的值

标签 python pandas

我需要通过 HashMap 根据其他列设置数据帧中的列的值。我无法通过现有的答案让它发挥作用。希望有好心的程序员能帮助我。

我有一个包含一些列的 df。我想添加一个新列,其中的值基于其他一些现有列。该值将根据 HashMap 设置。

这是从数据帧创建的 HashMap ;索引是一个元组:

material_code_map = dict([((a,b,c),i) for i, a,b,c in zip(df.Material,
                                                          df.Height,
                                                          df.Pole_Class,
                                                          df.Treatment)]) 

然后我有一个 df,其中包含 Material、Height、Pole_Class 等列。 在 df 中,我想添加“ Material ”列,其中“ Material ”是根据元组(高度、Pole_Class、治疗)从 map 派生的。

以下测试代码确实有效:

cleaned = cleaned.assign( Material_Number=lambda x: x.Pole_Class + x.Pole_Length )        
cleaned = cleaned.assign( Material_Number=lambda x: material_code_map[(30, 6, 'PENTA')] )

然而,这段代码似乎是显而易见的下一步,但它不起作用:

cleaned = cleaned.assign( Material_Number=lambda x: material_code_map[(x.Pole_Length, x.Pole_Class, 'PENTA')] ) 

我收到错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

感谢您帮我解决这个问题。

最佳答案

我终于找到了解决方案,我在这里分享它,以防它对像我这样的其他人有用。 我使用更简单的代码,专注于语法。 d 是映射表(字典),df 是包含 A 和 B 列的表; C 列通过映射 d 添加基于 A、B 的值。

In [12]: d
Out[12]: {(1, 1): 1, (1, 2): 2, (1, 3): 3, (1, 4): 4}

In [13]: df
Out[13]:
      A     B
0     1     2
1    11    22
2     1     3
3  1111  2222

In [14]: df['C'] = df[['A','B']].apply(tuple, axis=1).map(d)

In [15]: df
Out[15]:
      A     B    C
0     1     2  2.0
1    11    22  NaN
2     1     3  3.0
3  1111  2222  NaN

它也适用于字符串,正如我在我的例子中所需要的:

In [23]: d
Out[23]: {(1, 'a'): 1, (1, 'b'): 2, (1, 'c'): 3, (1, 'd'): 4}

In [24]: df
Out[24]:
      A     B
0     1     a
1    11    22
2     1     c
3  1111  2222

In [25]: df['C'] = df[['A','B']].apply(tuple, axis=1).map(d)

In [26]: df
Out[26]:
      A     B    C
0     1     a  1.0
1    11    22  NaN
2     1     c  3.0
3  1111  2222  NaN

In [27]:

关于python - 通过 HashMap 根据其他列设置或替换数据帧列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177261/

相关文章:

Python Pandas - 即使数据帧中存在相同的列,pd.merge 上也会出现 KeyError

python - 将 Pandas DataFrame 的各个部分 reshape 为宽格式

python - 将 SAS 数字转换为 python 日期时间

python - 使用第二列中的值从 pandas 列中删除特定数量的字母,Python

python - 如何忽略位于括号中的链接?

python - 使用 M2Crypto 创建任意 X509 扩展

python - 在 Python 中使用 NumPy 进行多元回归?

python - 如何通过查询压缩 pandas 行?

python - pandas:按二级索引范围对 MultiIndex 进行切片

Python列表列表初始化