在 pandas 系列中使用 if/else 根据条件创建新系列 [英] Using if/else in pandas series to create new series based on conditions

查看:95
本文介绍了在 pandas 系列中使用 if/else 根据条件创建新系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫df.假设我有一列活动"可以是有趣"或工作",我想将其转换为整数.我要做的是:

I have a pandas df. Say I have a column "activity" which can be "fun" or "work" and I want to convert it to an integer. What I do is:

df["activity_id"] = 1*(df["activity"]=="fun") + 2*(df["activity"]=="work") 

这是可行的,因为我不知道如何在其中放置 if/else(如果您有 10 个活动,它会变得复杂).

This works, since I do not know how to put an if/else in there (and if you have 10 activities it can get complicated).

但是,假设我现在遇到了相反的问题,我想从 id 转换为字符串,我不能再使用这个技巧了,因为我不能将字符串与布尔值相乘.我该怎么做?有没有办法使用if/else?

However, say I now have the opposite problem, and I want to convert from an id to a string, I cannot use this trick anymore because I cannot multiply a string with a Boolean. How do I do it? Is there a way to use if/else?

推荐答案

您可以创建一个以id为键,字符串为值的字典,然后使用map系列方法来转换整数到字符串.

You can create a dictionary with id as the key and the string as the value and then use the map series method to convert the integer to a string.

my_map = {1:'fun', 2:'work'}

df['activity']= df.activity_id.map(my_map)

这篇关于在 pandas 系列中使用 if/else 根据条件创建新系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆