我想在每一行中选择两个最大的值,对它们进行排序并获取列名作为值。其他值从数据框中删除。
import pandas as pd
d = {'col1': [1, 2, np.nan], 'col2': [2,3,3], 'col3': [3,6,5], 'col4': [4,9,10], 'col5': [5,1, np.nan], 'col6': [7,np.nan,2], 'col7': [np.nan, 5,6]}
df = pd.DataFrame(data=d)
我现在能够获得每行的两个最大值,但根据列值重塑数据框是另一项任务。下面的代码将其余的值保留为 Nan,这很好。但是如何重塑和获取列名?
lasttwo = df.stack().sort_values(ascending=True).groupby(level=0).tail(2).unstack()
示例:
--- | col1 | col2 | col3 | col4 | col5 | col6 | col7 |
---|---|---|---|---|---|---|---|
一 | 1 | 2 | 3 | 4 | 5 | 7 | 南 |
b | 2 | 3 | 6 | 9 | 1 | 南 | 5 |
c | 南 | 3 | 5 | 10 | 南 | 2 | 6 |
预期结果:
--- | --- | --- |
---|---|---|
一 | col6 | col5 |
b | col4 | col3 |
c | col4 | col7 |