python - 如何使用 python 从 pandas 数据框中排除某些列
问题描述
我有一个形状为(1000、200)的数据框。
有 1000 行和 200 列,我如何找到每行中最频繁的值并将该值添加到新列中。
我想从最终结果中排除前 5 列。
编码:
df['Mode'] = df.mode(axis=1).iloc[:, 0]
不能按要求工作并包括所有列。
解决方案
您需要 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]
推荐阅读
- c# - 使用 ODataQueryOptions 时无法应用 $select
- python - 如何在python中将一个矩阵分成两个矩阵?
- azure-devops - 如何更改 PR 合并提交消息?
- c++ - 如何清理或销毁 QJSEngine?
- javascript - 函数返回 int 返回 undefined
- vba - 通过 VBA 在 SQL 查询中使用通配符的字符串变量
- c# - 在插件中使用自定义附加属性会导致 Reflection/CreateInstance 出错
- django - 使用 Django 通道的 Angular Websocket 连接超时
- android - Android 5.1 中工具栏项上的黑色文本
- javascript - Vue | vue-moment.js 的问题