首页 > 解决方案 > 如何使用 python 从 pandas 数据框中排除某些列

问题描述

我有一个形状为(1000、200)的数据框。

有 1000 行和 200 列,我如何找到每行中最频繁的值并将该值添加到新列中。

我想从最终结果中排除前 5 列。

编码:

      df['Mode'] = df.mode(axis=1).iloc[:, 0]

不能按要求工作并包括所有列。

标签: pythonpython-3.xpandasdataframeindexing

解决方案


您需要 value_counts().idxmax() 并确保 axis=1

代码:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(low=1,high=6,size=(5,35)), columns=range(35))
print(df)
df['freq'] = df.apply((lambda x: (x[5:].mode())), axis=1)
print(df)

输出:

   0   1   2   3   4   5   6   7   8   9   10  11  12  13  ...  21  22  23  24  25  26  27  28  29  30  31  32  33  34
0   1   4   4   1   1   5   1   2   3   2   1   1   2   2  ...   1   5   3   2   2   1   2   5   5   4   4   4   2   3
1   5   1   1   4   5   2   3   4   1   2   4   5   2   3  ...   2   5   1   5   3   4   1   5   5   3   2   4   1   3
2   5   2   1   3   1   2   2   5   5   4   5   5   1   2  ...   3   3   5   5   1   4   2   4   3   2   2   4   3   3
3   4   4   2   2   3   4   5   1   3   1   2   5   4   5  ...   3   4   5   3   3   5   2   1   5   1   1   4   4   3
4   5   3   1   5   2   4   2   5   3   4   1   3   4   1  ...   3   1   4   4   3   1   5   4   3   2   2   1   3   3

[5 rows x 35 columns]
   0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  ...  21  22  23  24  25  26  27  28  29  30  31  32  33  34  freq
0  1  4  4  1  1  5  1  2  3  2   1   1   2   2   1  ...   1   5   3   2   2   1   2   5   5   4   4   4   2   3     2
1  5  1  1  4  5  2  3  4  1  2   4   5   2   3   1  ...   2   5   1   5   3   4   1   5   5   3   2   4   1   3     5
2  5  2  1  3  1  2  2  5  5  4   5   5   1   2   2  ...   3   3   5   5   1   4   2   4   3   2   2   4   3   3     2
3  4  4  2  2  3  4  5  1  3  1   2   5   4   5   4  ...   3   4   5   3   3   5   2   1   5   1   1   4   4   3     5
4  5  3  1  5  2  4  2  5  3  4   1   3   4   1   1  ...   3   1   4   4   3   1   5   4   3   2   2   1   3   3     3

[5 rows x 36 columns]

推荐阅读