在熊猫的最后一行中删除最高值的列

时间:2020-04-23 02:48:03

标签: python python-3.x pandas csv concatenation

我有多个一栏CSV文件,我使用pandas连接并找到均值:

#!/usr/bin/env python3

import os
import glob
import pandas as pd
from sys import argv, exit

os.chdir(f'{argv[1]}')
filenames = [i for i in glob.glob('*.csv')]
comb = pd.concat([pd.read_csv(f, header=None) for f in filenames], axis=1)
comb.columns = [f'Run {i+1}' for i in range(len(comb.columns))]
comb['Mean'] = comb.mean(numeric_only=True, axis=1)
comb.insert(loc=0, column='Epoch', value=[i+1 for i in range(len(comb))])
comb.to_csv(f'{argv[2]}', index=False)

argv[1]是要串联的目录,argv[2]是要保存串联文件的位置。输入示例如下:

0.6932
0.6605
0.634
0.5904
0.5339

和示例输出:

Epoch   Run 1   Run 2   Run 3   Run 4   Run 5   Mean
1   0.6932  0.6711  0.6687  0.6814  0.6903  0.684856667
2   0.6605  0.6326  0.6423  0.6323  0.6247  0.639423333
3   0.634   0.6003  0.6063  0.5928  0.5786  0.603956667
4   0.5904  0.5604  0.5576  0.5448  0.5276  0.559693333
5   0.5339  0.519   0.5068  0.496   0.4813  0.513653333

这是将五个一列,五行CSV文件串联在一起。

如何从该表中删除最后一行中编号最高的列?假设我要删除两列,在这种情况下为Run 1Run 2。所需的输出可能是:

Epoch   Run 3   Run 4   Run 5   Mean
1   0.6687  0.6814  0.6903  0.680133333
2   0.6423  0.6323  0.6247  0.6331
3   0.6063  0.5928  0.5786  0.592566667
4   0.5576  0.5448  0.5276  0.543333333
5   0.5068  0.496   0.4813  0.4947

pandas是否有内置功能可根据某一行的值删除列?我对给定列的最后一行感兴趣,并在其中删除了具有最高值的列。

1 个答案:

答案 0 :(得分:3)

这可能有些过分了:

to_drop = (df.filter(like='Run')  # choose only the `Run` columns
             .iloc[-1]            # and the last row
             .nlargest(2)         # two largest cells
             .index               # then the index, i.e. column names
          )

df = df.drop(to_drop, axis=1)