简体   繁体   English

检查列中是否存在值并在另一个 Pandas 中更改

[英]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 :您可以结合使用explodeisinagg.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.

相关问题 检查一个值是否存在于一列中,并根据不同的条件更改另一个 Pandas:Pandas - Check if a value exist in a column and change in another Pandas based on different conditions: Pandas 熊猫-根据另一列更改列中的值 - pandas - change value in column based on another column Pandas - 检查另一个数据框列中的系列值 - Pandas - check for series value in another dataframe column 如何检查Pandas中另一个dataframe中是否存在两列的组合值? - How to check if a combined value of two columns exist in another dataframe in Pandas? 大熊猫:列中存在检查值,该值存储为列表 - Pandas: Check value exist in a Column, which is stored as list 检查一列值是否在另一列中并创建列以在 Pandas 中指示 - Check if one column value is in another column and create column to indicate in Pandas Pandas - 检查列中的值是否是同一列中另一个值的 substring - Pandas - Check if a value in a column is a substring of another value in the same column Pandas:检查列中是否存在值,创建一个新列,存在则加1,如果不存在加0 - Pandas: Check if a value exist in a column, create a new column, exist add 1 if not add 0 根据其他列值更改pandas DataFrame列值 - Change a pandas DataFrame column value based on another column value 使用 pandas 根据另一列的值更改一列的值 - Change the value of a column based on the value of another column with pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM