[英]Check if a value exist in a column and change in another Pandas
I have the following information.我有以下信息。
Let's say I have the following list.假设我有以下列表。
my_list = [2,3,4,5]
My dataframe is as follows:我的dataframe如下:
df df
Col1 Value
[1,3,6] Hot
[7] Mild
[10,11,2] Cool
[5,9] Cool
[2,5,6] Mild
I would like to check if one of the value from the list my_list
exist in the column Col1
.我想检查列表
my_list
中的一个值是否存在于Col1
列中。 If it exist, change the value in Value
column to Hot
in the corresponding row.如果存在,将对应行的
Value
列的值改为Hot
。
I would like to see something like below.我想看到类似下面的东西。
Col1 Value
[1,3,6] Hot
[7] Mild
[10,11,2] Cool
[5,9] Hot
[2,5,6] Hot
I am just looking for a simple script that can iterate and check in every row and change a value in another column the corresponding row.我只是在寻找一个简单的脚本,它可以迭代并检查每一行,并在对应行的另一列中更改一个值。
Can any one help on this?有人可以帮忙吗?
You can use a combination of explode
, isin
, agg
, and .loc
:您可以结合使用
explode
、 isin
、 agg
和.loc
:
df.loc[df['Col1'].explode().isin(my_list).groupby(level=0).any(), 'Value'] = 'Hot'
Output: Output:
>>> df
Col1 Value
0 [1, 3, 6] Hot
1 [7] Mild
2 [10, 11, 2] Hot
3 [5, 9] Hot
4 [2, 5, 6] Hot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.