基于集合中的成员资格替换熊猫数据框中的值
我想替换 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
ISIN
检查Check with
isin
在条件 np.where 中使用 isin
Use isin in a conditional np.where