我有一个很大的df(64001行x 1600列),并且我既需要列名,又需要相应列的值。到目前为止,我设法获得了列名,并使用它们创建了一个数据框,如下所示。
原始数据框概述:
使用此代码:
df=df.apply(lambda s: s.abs().nlargest(5).index.tolist(), axis=1)
df=df.to_frame()
df[['MS_filename_1','MS_filename_2', 'MS_filename_3', 'MS_filename_4', 'MS_filename_5']] = pd.DataFrame(df[0].values.tolist(),index= df.index)
df = df.drop([0], axis=1)
输出:
我想要的输出将是另一个表格,如lastone,但它应该显示 Top n值(排名前1、2、3、4和列名称),而不是列名 5)。
我希望能一窥如何获得第二张桌子。
路易斯
答案 0 :(得分:1)
这是一种方法:
# minimal example
df = pd.DataFrame({'col1': pd.np.random.randint(2, 20, 6),
'col2': pd.np.random.randint(2, 20, 6),
'col3': pd.np.random.randint(2, 20, 6)})
# set it accordingly
topn = 2
newdf = df.apply(np.sort, axis=1).apply(lambda x: x[:n]).apply(pd.Series)
newdf.columns = ['MS_filename_1','MS_filename_2']
MS_filename_1 MS_filename_2
0 3 6
1 8 10
2 3 5
3 4 16
4 4 8
5 7 13
希望这给您一些想法。