python - 如何在 pandas 中列的值计数条件下采用相同的 DataFrame?
问题描述
我有一个pandas DataFrame,shape(1000,8)
所以我想制作新的DataFrame,但在一列中有条件但不是一个简单的条件,它是特定行上的值计数,例如我们有一列df.column1 = [1,2,2,2,3,3,4,5,8,8,8,8]
我有相同的DataFrame使用相同的列但在column1上有条件,我只想要column1的值重复超过3次的行,所以我得到:df.column1 = [8,8,8,8]
解决方案
您可以value_counts
只使用和保留最常用的值
import pandas as pd
# define df
df = pd.DataFrame()
df['column1'] = [1,2,2,2,3,3,4,5,8,8,8,8]
#get counts
counts = df['column1'].value_counts()
# keep only counts>3
counts = counts[counts>3]
# get the index to see which column1 values should be kept
to_keep = counts.index
# filter df with only correct values of column1
df.loc[df['column1'].isin(to_keep)]
# column1
#8 8
#9 8
#10 8
#11 8
推荐阅读
- c - 如何在c中用#define更改#include?
- angular - 堆积柱形图的数据标签未显示在角度项目的 Highcharts 中
- cordova - 如何修复服务响应丢失安装推荐人安装时间戳
- json - 如何从 Json api 制作动态侧边栏?
- xamarin - 如何使本地 ContentView 绑定标签文本
- c++ - 依赖于模板参数类型的静态 constexpr 类成员的初始化
- regex - Oracle:特殊字符过滤器几乎没有例外
- javascript - Express Next() return 404 not found
- javascript - 将变量定义为 let 和 var 显示 NaN
- react-native - 我怎样才能让我以前的 TextInput 值留在盒子里反应原生?