IF + AND 语句
IF + AND Statements
我在Python中有一个数据框形式的'Current Result'(在Excel中描述作为插图)。
我想添加一个列来分类某行是 'PRIME' 还是 'ALT' 指定。
判断某物是否为'ALT'的规则如下:
- 'Group' 列是 不是 'NaN'
- 和
- 'Utilization' 总是 0
嵌套的 IF / AND 语句是唯一可行的概念吗?还是有更有效的方法来做到这一点? PS 我是 Python 的新手。
添加数据框的示例代码:
import pandas as pd
### Generate data from lists.
data = {'Part':['AAA', 'BBB', 'CCC', 'DDD','EEE','FFF','GGG', 'HHH', 'III', 'JJJ', 'LLL','MMM','NNN'], 'Group':['', '', '', '','','45','45', '45', '', 'FF', 'FF','7J','7J'], 'Utl':['0', '0', '0', '0','0','100','0', '0', '0', '100', '0','100','0']}
### Create DataFrame
df = pd.DataFrame(data)
### Print the output.
print(df)
如果没有可消化的数据,re-create 有点难,但我相信这会为您提供所需的 IIUC
data = {
'Group' : [np.nan, None, np.nan, '7f', '7f', '7f', None, None, None, '4j', '4j', None, None, '4j'],
'Utilization':[0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 100, 0, 0, 99]
}
df = pd.DataFrame(data)
#This is here just in case you have some np.nan's instead of None it'll make everything the same
df['Group'] = df['Group'].replace({np.nan : None})
condition_list = [
(df['Group'].values == None) | ((df['Utilization']%2 == 0) & (df['Utilization'] > 0)),
(df['Group'].values != None) & (df['Utilization']%2 != 0) & (df['Utilization'] > 0),
(df['Group'].values != None) & (df['Utilization'] == 0)
]
choice_list = ['Prime', 'Alt', 'Alt']
df['Check'] = np.select(condition_list, choice_list, 0)
df
我在Python中有一个数据框形式的'Current Result'(在Excel中描述作为插图)。
我想添加一个列来分类某行是 'PRIME' 还是 'ALT' 指定。
判断某物是否为'ALT'的规则如下:
- 'Group' 列是 不是 'NaN'
- 和
- 'Utilization' 总是 0
嵌套的 IF / AND 语句是唯一可行的概念吗?还是有更有效的方法来做到这一点? PS 我是 Python 的新手。
添加数据框的示例代码:
import pandas as pd
### Generate data from lists.
data = {'Part':['AAA', 'BBB', 'CCC', 'DDD','EEE','FFF','GGG', 'HHH', 'III', 'JJJ', 'LLL','MMM','NNN'], 'Group':['', '', '', '','','45','45', '45', '', 'FF', 'FF','7J','7J'], 'Utl':['0', '0', '0', '0','0','100','0', '0', '0', '100', '0','100','0']}
### Create DataFrame
df = pd.DataFrame(data)
### Print the output.
print(df)
如果没有可消化的数据,re-create 有点难,但我相信这会为您提供所需的 IIUC
data = {
'Group' : [np.nan, None, np.nan, '7f', '7f', '7f', None, None, None, '4j', '4j', None, None, '4j'],
'Utilization':[0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 100, 0, 0, 99]
}
df = pd.DataFrame(data)
#This is here just in case you have some np.nan's instead of None it'll make everything the same
df['Group'] = df['Group'].replace({np.nan : None})
condition_list = [
(df['Group'].values == None) | ((df['Utilization']%2 == 0) & (df['Utilization'] > 0)),
(df['Group'].values != None) & (df['Utilization']%2 != 0) & (df['Utilization'] > 0),
(df['Group'].values != None) & (df['Utilization'] == 0)
]
choice_list = ['Prime', 'Alt', 'Alt']
df['Check'] = np.select(condition_list, choice_list, 0)
df