![](/img/trans.png)
[英]Check if a value exist in a column and change in another Pandas based on different conditions: Pandas
[英]Check if a value exist in a column and change in another Pandas
我有以下信息。
假設我有以下列表。
my_list = [2,3,4,5]
我的dataframe如下:
df
Col1 Value
[1,3,6] Hot
[7] Mild
[10,11,2] Cool
[5,9] Cool
[2,5,6] Mild
我想檢查列表my_list
中的一個值是否存在於Col1
列中。 如果存在,將對應行的Value
列的值改為Hot
。
我想看到類似下面的東西。
Col1 Value
[1,3,6] Hot
[7] Mild
[10,11,2] Cool
[5,9] Hot
[2,5,6] Hot
我只是在尋找一個簡單的腳本,它可以迭代並檢查每一行,並在對應行的另一列中更改一個值。
有人可以幫忙嗎?
您可以結合使用explode
、 isin
、 agg
和.loc
:
df.loc[df['Col1'].explode().isin(my_list).groupby(level=0).any(), 'Value'] = 'Hot'
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.