AttributeError: 'str' object has no attribute 'union'

AttributeError: 'str' object has no attribute 'union'

当我使用下面的代码时,出现属性错误。

我的代码:

df_1.loc[df_2.year <= 5, 'old']\
        = (df_1.loc[df_2.year<= 5, 'old'].apply(lambda x:x.union({'old 
          product, '})))

错误:

AttributeError: 'str' object has no attribute 'union'

我已经回答了很多关于属性错误的问题。但是,我还是不明白为什么会出现这个错误。

df1: | |年份 | | -----| ---- | | 0 | 5 | | 1 | 0 | | 2 | 1 | | 3 | 9 | | 4 | 2 | | 5 | 0 |

df2: | |品牌| | -----| ---- | | 0 |年 | | 1 | ABB | | 2 |凯伊 | | 3 |好时通 | | 4 |天天 | | 5 | 0TY |

Python string 对象没有 union 函数。您可以使用 + 代替-

df_1.loc[df_2.year <= 5, 'old'] = (df_1.loc[df_2.year<= 5, 'old'].apply(lambda x: x + 'old product, ' if isinstance(x, str) else x.union({'old product, '})))

更多示例请参考 here