使用 np.where 和 np.select 的条件语句
Conditional statements using np.where and np.select
尝试根据特定字符串是否存在于不同的列中来填充数据框中的列。我可以用一系列嵌套的 np.where
语句来做到这一点,例如:
cond1=df.CollectType.str.contains('Outcrop')
cond2=df.CollectType.str.contains('Chip channel')
cond3=df.CollectType.str.contains('Rubble')
cond4=df.CollectType.str.contains('Float')
cond5=df.CollectType.str.contains('Dump')
df['R_SampleType'] = np.where(cond1, 'Outcrop', np.where(cond2,
'Chip channel', np.where(cond3,'Rubble',
np.where(cond4,'Float',
np.where(cond5,'Dump','')))))
但这似乎不是很有效。所以,我试图列出条件并调用列表:
values = ['Outcrop', 'Chip Channel','Rubble','Float','Dump']
conditions = list(map(df['CollectType'].str.contains, values))
df['R_SampleType'] = np.select(conditions, values, '')
但我收到错误:
ValueError: invalid entry 0 in condlist: should be boolean ndarray
有什么建议吗?
看来你只是想复制一列,然后在不满足条件的地方放一个空字符串。
如果是这种情况,这里有一个解决方案:
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")
可重现的例子:
from random import choices
values_ok = ["Outcrop", "Chip channel", "Rubble", "Float", "Dump"]
values_nok = ["Not", "A", "Valid", "Value"]
num_items = 15
df = pd.DataFrame(
choices(values_ok + values_nok, k=num_items), columns=["CollectType"]
)
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")
尝试根据特定字符串是否存在于不同的列中来填充数据框中的列。我可以用一系列嵌套的 np.where
语句来做到这一点,例如:
cond1=df.CollectType.str.contains('Outcrop')
cond2=df.CollectType.str.contains('Chip channel')
cond3=df.CollectType.str.contains('Rubble')
cond4=df.CollectType.str.contains('Float')
cond5=df.CollectType.str.contains('Dump')
df['R_SampleType'] = np.where(cond1, 'Outcrop', np.where(cond2,
'Chip channel', np.where(cond3,'Rubble',
np.where(cond4,'Float',
np.where(cond5,'Dump','')))))
但这似乎不是很有效。所以,我试图列出条件并调用列表:
values = ['Outcrop', 'Chip Channel','Rubble','Float','Dump']
conditions = list(map(df['CollectType'].str.contains, values))
df['R_SampleType'] = np.select(conditions, values, '')
但我收到错误:
ValueError: invalid entry 0 in condlist: should be boolean ndarray
有什么建议吗?
看来你只是想复制一列,然后在不满足条件的地方放一个空字符串。
如果是这种情况,这里有一个解决方案:
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")
可重现的例子:
from random import choices
values_ok = ["Outcrop", "Chip channel", "Rubble", "Float", "Dump"]
values_nok = ["Not", "A", "Valid", "Value"]
num_items = 15
df = pd.DataFrame(
choices(values_ok + values_nok, k=num_items), columns=["CollectType"]
)
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")