在 python 的数据框中的每一行中查找最大值
Finding highest values in each row in a data frame for python
我想在每一行和 return 列 header 中找到最大值,以获取 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
这为我们提供了每一行的最高值,但保留了原始列,导致难看的 NaN 值,其中一列并非处处都是前 n 个值的一部分。实际上,我们想要接收 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
快到了。剩下的就是将 Index 对象转换为 Series。
解决方案
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()
函数,因为我不想 保留原始索引。
我想在每一行和 return 列 header 中找到最大值,以获取 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
这为我们提供了每一行的最高值,但保留了原始列,导致难看的 NaN 值,其中一列并非处处都是前 n 个值的一部分。实际上,我们想要接收 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
快到了。剩下的就是将 Index 对象转换为 Series。
解决方案
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()
函数,因为我不想 保留原始索引。