我有一個資料幀的資料幀 影像
我需要將teleport_value 復制到值列僅適用于列規則為'teleport' 且列值為''的情況,在其他情況下,列值的欄位將保持不變。
因此,資料框將如下所示:請求的資料幀的 影像
uj5u.com熱心網友回復:
在問題中描述的列上寫下條件,并將輸出分配給value. 一種選擇是numpy.where用于此類情況。請注意,還有許多其他方法可以實作相同的目標。
import numpy as np
import pandas as pd
# You don't need this part of the code, I used it to recreate the
# dataframe, as you have shared a link to a screenshot..
df = pd.DataFrame({
'operator': np.array([[i] * 3 for i in ['First', 'Second', 'Third']]).flatten(),
'solution': ['row'] * 9,
'rule': ['allow', 'block', 'teleport'] * 3,
'value': [1, 0, '', 0, 1, 'loc', 1, 1, ''],
'teleport_value': ['', '', 'value'] [''] * 5 ['value']
})
# Solution: I have put the comments with your own words from question,
# so that you know what does each line..
df['value'] = np.where(
(
(df['rule'] == 'teleport') & # row with column rule is 'teleport' AND
(df['value'] == '') # column value is ''
),
df['teleport_value'], # copy teleport_value to value column
df['value'] # in other cases the field of column value will be without changes
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392013.html
上一篇:根據條件更改列的值:Pandas
