我希望能够在Python中找到每行最大的值,并返回该值所在的列标题。例如,我想找到每行中前两个最大的值:
df =
A B C D
5 9 8 2
4 1 2 3
我希望输出的结果看起来像这样:
df =
B C
A D
largest_n
个最大值。我先对数据框进行了转置,然后对每一列应用nlargest
函数。我使用.index.tolist()
来提取所需的top_n
列。最后,我再次对数据框进行转置,使其恢复到所需的形状。top_n = 2
>>> pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist()
for n, col in enumerate(df.T)}).T
0 1
0 B C
1 A D
我决定采用另一种方法:对每行应用pd.Series.nlargest()
函数。
解决方案路径
>>> df.apply(pd.Series.nlargest, axis=1, n=2)
A B C D
0 NaN 9.0 8.0 NaN
1 4.0 NaN NaN 3.0
这使我们获得每行的最高值,但保留原始列,导致在某一列不被包含在前n个最大值中时出现难看的NaN值。实际上,我们想要接收nlargest()
结果的索引。
>>> df.apply(lambda s, n: s.nlargest(n).index, axis=1, n=2)
0 Index(['B', 'C'], dtype='object')
1 Index(['A', 'D'], dtype='object')
dtype: object
就快完成了,唯一剩下的就是将索引对象转换为系列。
解决方案
df.apply(lambda s, n: pd.Series(s.nlargest(n).index), axis=1, n=2)
0 1
0 B C
1 A D
请注意,我没有使用Index.to_series()
函数,因为我不想保留原始索引。
nlargest
方法。 - cowlicks