Python - np.Where 条件

Python - np.Where condition

我正在与 pandas 合作,我有这个 table(产品)

id quantity type
1 18 pack
2 pack 3
3 6 pack
4 pack 6
5 6 9

我想做一个when条件来帮助我整理错误插入的信息

id quantity type
1 18 pack
2 3 pack
3 6 pack
4 6 pack
5 6 9

我只想在 SQL 服务器上使用 ISNUMERIC(),如何在 Python 上实现?

我试过了

np.where(np.isnumeric(type),prod['quantity'],prod['type'))

对我做错了什么有任何反馈吗?

谢谢!

prod = pd.DataFrame({'quantity': [18, 'pack', 6, 'pack', 6], 'type': ['pack', 3, 'pack', 6, 9]}, index=[1, 2, 3, 4, 5])
prod.index.name = 'id'

cond = prod.type.astype(str).str.isnumeric() & ~prod.quantity.astype(str).str.isnumeric()
# or 
# cond = prod.quantity.map(lambda x: isinstance(x, str))  # to swap if some values in the 'quantity' column is str
prod.loc[cond, ['type', 'quantity']] = prod.loc[cond, ['quantity', 'type']].values # based on 
print(prod)

输出:

   quantity  type
id               
1        18  pack
2         3  pack
3         6  pack
4         6  pack
5         6     9