基于集合中的成员资格替换熊猫数据框中的值

发布于 2025-01-18 05:37:35 字数 457 浏览 1 评论 0原文

我想替换 pandas 数据框中的值(如果它们包含在集合中)。这是一个小示例:

lset = frozenset((0,1))
data = {'col1': [3, 2, 1, 0]}
df = pd.DataFrame.from_dict(data)

我希望将 lset 中包含的 col1 的所有值替换为 -5。结果相当于:

data = {'col1': [3, 2, -5, -5]}
df = pd.DataFrame.from_dict(data)

我尝试了

df.loc[df['col1'] in lset, 'col1'] = -5

,但收到了 TypeError: unhashable type: 'Series'

I want to replace the values in a pandas dataframe if they are contained in a set. Here is a mini-example:

lset = frozenset((0,1))
data = {'col1': [3, 2, 1, 0]}
df = pd.DataFrame.from_dict(data)

I want all the values of col1 contained in lset to be replaced by -5. The result would be equivalent to:

data = {'col1': [3, 2, -5, -5]}
df = pd.DataFrame.from_dict(data)

I tried

df.loc[df['col1'] in lset, 'col1'] = -5

but I'm getting TypeError: unhashable type: 'Series'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

緦唸λ蓇 2025-01-25 05:37:35

使用ISIN检查

df.loc[df['col1'].isin(lset), 'col1'] = -5
df
Out[180]: 
   col1
0     3
1     2
2    -5
3    -5

Check with isin

df.loc[df['col1'].isin(lset), 'col1'] = -5
df
Out[180]: 
   col1
0     3
1     2
2    -5
3    -5
贪了杯 2025-01-25 05:37:35

在条件 np.where 中使用 isin

df['col2']=np.where(df['col1'].isin(lset),-5,df['col1'])



   col1  col2
0     3     3
1     2     2
2     1    -5
3     0    -5

Use isin in a conditional np.where

df['col2']=np.where(df['col1'].isin(lset),-5,df['col1'])



   col1  col2
0     3     3
1     2     2
2     1    -5
3     0    -5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文