简体   繁体   English

Python - np.Where 条件

[英]Python - np.Where condition

I'm working with pandas and I have this table (prod)我正在和熊猫一起工作,我有这张桌子(产品)

id ID quantity数量 type类型
1 1 18 18 pack
2 2 pack 3 3
3 3 6 6 pack
4 4 pack 6 6
5 5 6 6 9 9

I'm want to do a when condition to help me sort out wrong inserted information我想做一个when条件来帮我整理错误插入的信息

id ID quantity数量 type类型
1 1 18 18 pack
2 2 3 3 pack
3 3 6 6 pack
4 4 6 6 pack
5 5 6 6 9 9

I would simply use ISNUMERIC() on SQL Server, how can I achieve this on Python?我只想在 SQL Server 上使用 ISNUMERIC(),如何在 Python 上实现这一点?

I have tried我试过了

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

any feedback on what I'm doing wrong?关于我做错了什么的任何反馈?

thanks!谢谢!

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 https://stackoverflow.com/a/25792812/15035314
print(prod)

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM