我有一个 Dataframe ,其中有两列,first_columns 和 secondary_columns。 first_columns 是 id,second_columns 是房间号。
正如您从图片中看到的那样,特定的 id 人在不同的房间号上服务。现在我想在给定条件下将所有第二列替换为 1 和零
1) 如果特定的first_columns列id人员不在9、10和11中服务,则将所有房间号替换为1,如果他工作则将所有房间号替换为0。
上图中,first_columns id 3737在9,10,11房间不起作用。那么3737房间号的所有行将被替换为1。
最佳答案
我认为需要groupby
与 transform
通过 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/