我有以下資訊。
假設我有以下串列。
my_list = [2,3,4,5]
我的資料框如下:
df
Col1 Score Value
[1,3,6] 0 Hot
[7] 10 Mild
[10,11,2] 50 Cool
[5,9] 0 Cool
[2,5,6] 100 Mild
我想檢查列 Col1 中是否存在串列 my_list 中的值之一。如果存在,通過檢查是否Score > 0將值列中的值更改為相應行中的熱值,除非保持值列中的值不變。
我想看到類似下面的內容。
Col1 Score Value
[1,3,6] 0 Hot
[7] 10 Mild
[10,11,2] 50 Hot
[5,9] 0 Cool
[2,5,6] 100 Hot
我只是在尋找一個簡單的腳本,它可以迭代和檢查每一行并更改相應行另一列中的值。
任何人都可以對此提供幫助嗎?
uj5u.com熱心網友回復:
首先explodeCol1 檢查值是否在 my_list 中,然后groupby any獲取一系列布林值(如果串列中至少有一個專案,則為 True)。
mask如果滿足兩個條件,則使用此條件和 Score to the Value with "Hot" 條件:
match = df['Col1'].explode().isin(my_list).groupby(level=0).any()
df['Value'] = df['Value'].mask(match & df['Score'].gt(0), 'Hot')
輸出:
Col1 Score Value
0 [1, 3, 6] 0 Hot
1 [7] 10 Mild
2 [10, 11, 2] 50 Hot
3 [5, 9] 0 Cool
4 [2, 5, 6] 100 Hot
uj5u.com熱心網友回復:
這是一種使用map()and的方法where():
s1 = df['col1'].map(lambda x: any([i in my_list for i in x]))
s2 = df['Score'].eq(0)
df.assign(Value = df['Value'].where((s1 | s2),df['Value']))
輸出:
col1 Score Value
0 [1, 3, 6] 0 Hot
1 [7] 10 Mild
2 [10, 11, 12] 50 Hot
3 [5, 9] 0 Cool
4 [2, 5, 6] 100 Hot
uj5u.com熱心網友回復:
你可以用 apply
df=["Value"] =(df.apply(lambda x: "Hot" if len(set(x["Col1"]).intersection(my_list)) >0
and x["Score"] >0 else x["Value"],axis=1) )
輸出:
col1 Score Value
0 [1, 3, 6] 0 Hot
1 [7] 10 Mild
2 [10, 11, 12] 50 Hot
3 [5, 9] 0 Cool
4 [2, 5, 6] 100 Hot
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390600.html
