python - 如何在给定条件下替换数据框列?

标签 python pandas dataframe

我有一个 Dataframe ,其中有两列,first_columns 和 secondary_columns。 first_columns 是 id,second_columns 是房间号。 enter image description here

正如您从图片中看到的那样,特定的 id 人在不同的房间号上服务。现在我想在给定条件下将所有第二列替换为 1 和零

1) 如果特定的first_columns列id人员不在9、10和11中服务,则将所有房间号替换为1,如果他工作则将所有房间号替换为0。

上图中,first_columns id 3737在9,10,11房间不起作用。那么3737房间号的所有行将被替换为1。

最佳答案

我认为需要groupbytransform通过 set 进行比较,最后通过 ~ 反转掩码并转换为整数:

df['new'] = ((~df.groupby('first_column')['second_column']
                .transform(lambda x: set(x) >=set([9,10,11])))
                .astype(int))
print (df)
    first_column  second_column  new
0           3767              2    1
1           3767              4    1
2           3767              6    1
3           6282              2    0
4           6282              9    0
5           6282             10    0
6           6282             11    0
7          10622              0    1
8          13096              7    1
9          13096             10    1
10         13896             11    1

关于python - 如何在给定条件下替换数据框列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49571382/

相关文章:

python - 狮身人面像自定义模板

python - 如何根据条件将 csv 文件合并到单个文件并将文件名添加为列?

python - Pandas .txt文件到.csv文件缺少行

python - 合并某些行不相同的多个数据框

python - 如何根据列名删除列python pandas

python - 拆分列表后加入相关项目

python - 关于 git push heroku 主命令的错误,pywin32 错误

javascript - 如何使用 javascript 客户端设置 Python 服务器端

python-3.x - 安装了 pandas 但仍然无法导入

python - 过滤列值并收到 future 警告和类型错误?