python - How to create column that contains the column name from the row max of a list of columns
问题描述
I have a df that looks like this:
time A B C
0 0 19 19
1 0 4 4
2 0 0 0
3 0 0 0
4 0 4 4
I want to create a new column that yields the column name for highest value per row between columns A, B, and C. If all values are 0, it should yield NaN. If there is a tie, then it should yield both values. There is a helpful answer here that I am starting with, but this function yields the first column name when all columns are 0 and doesn't handle ties.
name of column, that contains the max value
What I want is this:
time A B C MAX
0 0 18 19 C
1 0 4 4 [B,C]
2 0 0 0 NaN
3 0 0 0 NaN
4 10 4 4 A
解决方案
您可以使用应用:
def ma(xs):
lst = [name for name, x in zip(xs.index, xs) if x == max(xs) and x > 0]
if len(lst) == 1:
return lst[0]
return lst or np.nan
df['max'] = df[['A', 'B', 'C']].apply(ma, axis=1)
print(df)
输出
time A B C max
0 0 0 18 19 C
1 1 0 4 4 [B, C]
2 2 0 0 0 NaN
3 3 0 0 0 NaN
4 4 10 4 4 A
推荐阅读
- sas - A中的commun列的值被SAS中的函数merge替换为B中的值
- android - 我对 Android Auto 媒体持续时间功能有疑问
- r - 如何使用 gsub 从字符串中删除字符,但有例外
- spring-boot - 使用 Gradle 的 Spring Boot 项目中的自定义属性
- python - 从 3D DICOM 图像重建 2D X 射线
- r - 返回与字符串向量关联的值向量?
- java - 如何在 lambda 函数中延迟初始化 Map?
- android - 存储访问框架:查询用户选择的文件夹 uri 时出现不支持的 Uri 错误
- c# - 防止 IHttpClientFactory 为处理程序创建 DI 范围
- .net - 哪个控制 TabIndex 的“重新启动”编号?