python - 使用 np.where 和 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="")
推荐阅读
- grpc - java - 如何从java中的grpc请求中获取请求头?
- powerbi - 在 Power BI 中合并两个表
- javascript - 单击会不必要地进行两次 ajax 调用,并且在我刷新页面之前 DOM 不会更新
- azure-storage - 如何为 Azure Databricks 配置 Azure Storage Gen 2
- ocr - 如何在正在运行的程序窗口上执行 OCR
- apache-spark - 如何为 spark 作业确定更好的 spark.sql.shuffle.partitions 编号
- plot - 在八度图中更改轴的比例
- amazon-web-services - 重启后无法通过公网 IP 访问 EC2 实例
- java - Spoonacular 无效的 api 密钥
- java - 在 Java 中使用 GPU 的最简单方法