python - Pandas 根据条件在多列中找到第一个非零条目
问题描述
我有一个这样的数据框 -
Alpha Id Col1 Col2 Col3 Col4
0 a Col3 0 0 10 34
1 b Col2 0 5 0 4
2 c Col1 16 0 3 0
3 d Col2 0 0 0 9
4 e Col3 0 0 18 0
5 f Col1 0 14 0 29
对于每一行,我需要找到在指定的列之后出现的第一个非零值的列名ID
这样生成的数据框看起来像这样 -
Alpha Id Col1 Col2 Col3 Col4 Result
0 a Col3 0 0 10 34 Col4
1 b Col2 0 5 0 4 Col4
2 c Col1 16 0 3 0 Col3
3 d Col2 0 0 0 9 Col4
4 e Col3 0 0 18 0 0
5 f Col1 0 14 0 29 Col2
我知道idxmax()
可用于连续获取第一个非零条目。但是我怎样才能在这里指定条件呢?
提前感谢任何解决方案/提示。
解决方案
利用:
#compare last 4 columns by Id column with broadcasting
a = df.columns[-4:].to_numpy() == df['Id'].to_numpy()[:, None]
#print (a)
#shifting by 1 values, check next matching by cumulative sum and compare for not equal
m1 = np.cumsum(a[:, :-1], axis=1) != 0
#compare last 3 columns
m2 = df.iloc[:, -3:].ne(0)
#chain masks by bitwise AND
m = m1 & m2
#get values of index if at least one True per row else 0
df['new'] = np.where(m.any(axis=1), m.idxmax(axis=1), 0)
print (df)
Alpha Id Col1 Col2 Col3 Col4 new
0 a Col3 0 0 10 34 Col4
1 b Col2 0 5 0 4 Col4
2 c Col1 16 0 3 0 Col3
3 d Col2 0 0 0 9 Col4
4 e Col3 0 0 18 0 0
5 f Col1 0 14 0 29 Col2
推荐阅读
- java - 为什么我没有在 intellij 的类旁边运行图标?
- azure-api-management - 如何使用 azure api 管理进行自定义访问令牌检查并丰富请求中的数据
- spring-cloud-function - 如何使用消息流测试 Spring Cloud Function
- r - 将功能应用于特定列,同时保留其他列
- java - SimpleDateFormat 显示不一致的结果
- angularjs - Angular 代码在 Visual Studio 中工作,但在 IIS 中不工作
- dictionary - AttributeError:“dict”对象没有属性“append”并且测试失败
- sql-server - SQL Server 数据工具安装在 5 小时后安装 80% 后卡住
- sql - PostgreSQL查询:获取简洁的数字串
- c# - 常规 LINQ 方法链接中间的表达式树;动态和可空类型?