文档主要记录一些关于对多列同一行的操作:
- 按行求和、最大值、最小值;
- 按行求最小值的对应的列名;
1.数据导入
import pandas as pd
excel_file = r'/Users/xiaokkk/Desktop/elec_res.xlsx'
elec_res = pd.read_excel(excel_file)
elec_res.head()
| 日期 | y1 | y2 | y3 | y4 | y5 |
---|
0 | 2022-06-29 | 27 | 18 | 24 | 3 | 2 |
---|
1 | 2022-06-29 | 14 | 20 | 28 | 6 | 34 |
---|
2 | 2022-06-29 | 35 | 36 | 18 | 7 | 37 |
---|
2.按行求和、最大值、最小值
col_list = elec_res.columns.tolist()
col_list[1:]
['y1', 'y2', 'y3', 'y4', 'y5']
elec_res['y'] = elec_res[col_list[1:]].T.sum()
elec_res
| 日期 | y1 | y2 | y3 | y4 | y5 | y |
---|
0 | 2022-06-29 | 27 | 18 | 24 | 3 | 2 | 74 |
---|
1 | 2022-06-29 | 14 | 20 | 28 | 6 | 34 | 102 |
---|
2 | 2022-06-29 | 35 | 36 | 18 | 7 | 37 | 133 |
---|
elec_res['y_min'] = elec_res[col_list[1:]].T.min()
elec_res['y_max'] = elec_res[col_list[1:]].T.max()
elec_res
| 日期 | y1 | y2 | y3 | y4 | y5 | y | y_min | y_max |
---|
0 | 2022-06-29 | 27 | 18 | 24 | 3 | 2 | 74 | 2 | 27 |
---|
1 | 2022-06-29 | 14 | 20 | 28 | 6 | 34 | 102 | 6 | 34 |
---|
2 | 2022-06-29 | 35 | 36 | 18 | 7 | 37 | 133 | 7 | 37 |
---|
3.按行求和、最大值、最小值
elec_res_t = elec_res.T.reset_index().iloc[1:,:]
elec_res_t.head()
| index | 0 | 1 | 2 |
---|
1 | y1 | 27 | 14 | 35 |
---|
2 | y2 | 18 | 20 | 36 |
---|
3 | y3 | 24 | 28 | 18 |
---|
4 | y4 | 3 | 6 | 7 |
---|
5 | y5 | 2 | 34 | 37 |
---|
a = []
for i in range(0,elec_res.shape[0]):
a.append(elec_res_t.loc[elec_res_t[i] == min(elec_res_t[i]),'index'].iloc[0])
elec_res['y_min_index'] = a
elec_res
| 日期 | y1 | y2 | y3 | y4 | y5 | y | y_min | y_max | y_min_index |
---|
0 | 2022-06-29 | 27 | 18 | 24 | 3 | 2 | 74 | 2 | 27 | y5 |
---|
1 | 2022-06-29 | 14 | 20 | 28 | 6 | 34 | 102 | 6 | 34 | y4 |
---|
2 | 2022-06-29 | 35 | 36 | 18 | 7 | 37 | 133 | 7 | 37 | y4 |
---|