根据其他列中的最大值填充列(python pandas)
问题描述:
我有一个包含每列(A,B,C)中的值的表。 我想用具有最大值的列的名称创建另一列(max_col)。因此,如果A列大于B或C,则填充“A”。根据其他列中的最大值填充列(python pandas)
下面的代码有效,但在很多不同的列可供选择的情况下,它不是非常“pythonic”或可伸缩的。
import pandas as pd
import numpy as np
table = { 'A': [1,2,3,4,5,6],
'B':[2,4,1,5,3,8],
'C':[3,1,2,4,5,6]}
df = pd.DataFrame.from_dict(table)
df['total'] = df.max(axis=1)
df['max_col'] = np.nan
df['max_col'] = np.where(df['total'] == df['A'],'A',df['max_col'])
df['max_col'] = np.where(df['total'] == df['B'],'B',df['max_col'])
df['max_col'] = np.where(df['total'] == df['C'],'C',df['max_col'])
df
此外,该代码被朝最后一列偏压被检查,在第5行的情况下,A和C值是相同的,但“max_col”被填充以“C”,因为它是最后被检查。理想情况下,'max_col'在这种情况下会填充'No Max'。
答
使用DataFrame.idxmax
获取最大值的列。
但是,如果有多个最大值,得到的布尔面具与max
比较所有值,然后总结True
秒 - >True
s为像1
S程序。因此,对于最终的掩码获得更大的值,如1
。
df['max_col'] = np.where(df.eq(df.max(axis=1), axis=0).sum(axis=1) > 1,
'No Max',
df.idxmax(axis=1))
print (df)
A B C max_col
0 1 2 3 C
1 2 4 1 B
2 3 1 2 A
3 4 5 4 B
4 5 3 5 No Max
5 6 8 6 B
详情:
print (df.eq(df.max(axis=1), axis=0))
A B C
0 False False True
1 False True False
2 True False False
3 False True False
4 True False True
5 False True False
print (df.eq(df.max(axis=1), axis=0).sum(axis=1))
0 1
1 1
2 1
3 1
4 2
5 1
dtype: int64
print (df.idxmax(axis=1))
0 C
1 B
2 A
3 B
4 A
5 B
dtype: object
与numpy的广播类似的解决方案:
arr = df.values
mask = (arr == arr.max(axis=1)[:, None]).sum(axis=1) > 1
df['max_col'] = np.where(mask, 'No Max', df.idxmax(axis=1))
print (df)
A B C max_col
0 1 2 3 C
1 2 4 1 B
2 3 1 2 A
3 4 5 4 B
4 5 3 5 No Max
5 6 8 6 B
编辑的评论:
cols = ['A','B']
df['max_col'] = np.where(df[cols].eq(df[cols].max(axis=1), axis=0).sum(axis=1) > 1,
'No Max',
df[cols].idxmax(axis=1))
print (df)
A B C max_col
0 1 2 3 B
1 2 4 1 B
2 3 1 2 A
3 4 5 4 B
4 5 3 5 A
5 6 8 6 B
0123:
您可以通过子集过滤列
很好,谢谢你的快速回答。你知道什么是最好的方法来做比较只有有限的列。比方说,列A,B和C是更大数据框的一部分,我不想与其他列进行比较? – Jelmerd