- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Pandas 新手,我想执行类似 Reduce number of levels for large categorical variables 的操作(分类变量的分箱以降低其水平)以下代码在 R 中运行良好
DTsetlvls <- function(x, newl)
setattr(x, "levels", c(setdiff(levels(x), newl), rep("other", length(newl))))
我的数据框:
df = pd.DataFrame({'Color': 'Red Red Blue'.split(),
'Value': [100, 150, 50]})
df['Counts'] = df.groupby('Color')['Value'].transform('count')
print (df)
Color Value Counts
0 Red 100 2
1 Red 150 2
2 Blue 50 1
我会手动创建一个聚合列,然后基于该列标记不太频繁的组,例如“蓝色”作为单个“其他”组。但与简洁的 R 代码相比,这似乎很笨拙。这里正确的方法是什么?
最佳答案
您可以使用value_counts
与 numpy.where
,其中条件为 isin
。
如果您的变量是对象类型,请参见下文。如果您的变量属于类别类型,则向下跳至底部。
df = pd.DataFrame({'Color':'Red Red Blue Red Violet Blue'.split(),
'Value':[11,150,50,30,10,40]})
print (df)
Color Value
0 Red 11
1 Red 150
2 Blue 50
3 Red 30
4 Violet 10
5 Blue 40
a = df.Color.value_counts()
print (a)
Red 3
Blue 2
Violet 1
Name: Color, dtype: int64
#get top 2 values of index
vals = a[:2].index
print (vals)
Index(['Red', 'Blue'], dtype='object')
<小时/>
df['new'] = np.where(df.Color.isin(vals), 0,1)
print (df)
Color Value new
0 Red 11 0
1 Red 150 0
2 Blue 50 0
3 Red 30 0
4 Violet 10 1
5 Blue 40 0
或者,如果需要替换所有非顶级值,请使用 where
:
df['new1'] = df.Color.where(df.Color.isin(vals), 'other')
print (df)
Color Value new1
0 Red 11 Red
1 Red 150 Red
2 Blue 50 Blue
3 Red 30 Red
4 Violet 10 other
5 Blue 40 Blue
<小时/>
对于类别类型:
df = pd.DataFrame({'Color':'Red Red Blue Red Violet Blue'.split(),
'Value':[11,150,50,30,10,40]})
df.Color = df.Color.astype('category')
a= df.Color.value_counts()[:2].index
print(a)
CategoricalIndex(['Red', 'Blue'],
categories=['Blue', 'Red', 'Violet'],
ordered=False, dtype='category')
请注意,紫罗兰色仍然是一个类别。所以我们需要.remove_unused_categories()
.
vals = df.Color.value_counts()[:2].index.remove_unused_categories()
CategoricalIndex(['Red', 'Blue'],
categories=['Blue', 'Red'],
ordered=False, dtype='category')
正如评论中提到的,设置新变量时会发生 ValueError 。解决这个问题的方法是改变类型。
df['new1'] = df.Color.astype('object').where(df.Color.isin(vals), 'other')
df['new1'] = df['new1'].astype('category')
关于python - Pandas 减少 value_counts() 表格中分类变量的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39099217/
比如我得到的dataframe如下: PassengerId Survived Pclass 0 1 0 3 1 2
我有一个数据框,我想查找每个值出现的次数。当我使用这个命令时 test = df['name'].value_counts() 我得到了正确的结果,但是当我尝试这个 df['occ'] = df['n
我有一个 excel 文件,其中有一列包含多个单词。我正在尝试计算每个单词的出现频率。所以如果我有一个列表 Labels a a b b c c c 输出应该是 c : 3 b : 2 a : 2 我
这个问题在这里已经有了答案: How to count the same values in a dict? [duplicate] (1 个回答) 关闭 3 年前。 我很熟悉如何返回value_c
我正在尝试使用 pandas(v0.23.4 ).当所有类别都存在时,这工作正常: import calendar import random import pandas as pd random.s
我有以下列connect_start 0 2019-01-01 00:01:44 1 2019-01-01 00:02:57 2 2019-01-01 00:24:09 3 2019-
我需要计算大量独立列中的值的计数(例如由 value_counts 表示),这些独立列由一组固定的 2-5 个其他列分组。此练习是对多达数百万行和多达 50-100 列的数据进行数据挖掘的一部分。因此
我正在尝试计算 pandas df 的嵌套列的唯一值,这是 manuel 注释的结果。假设我们有以下 df: df_test = pd.DataFrame(data=dict(x=["A","B","
在pandas里面常用value_counts确认数据出现的频率。 1. Series 情况下: pandas 的 value_counts() 函数可以对Series里面的每个值进行计数并且排
我得到了以下数据框: ae264e3637204a6fb9bb56bc8210ddfd ... 2906b810c7d4411798c6938adc9daaa5 1
我有一个由 df.column.value_counts().sort_index() 生成的 Pandas 系列。 | N Months | Count | |------|------| |
我有以下数据框: import pandas as pd import numpy as np df_Station_Weather = pd.DataFrame(
我创建了一个由两列组成的数据框。我想计算这两列出现的次数。 数据框看起来像 - No Name 1 A 1 A 5 T 9 V Nan M 5 T 1 A 我想使用 valu
我有一个数据框,其中一列是带有以下标签的分类变量:['Short', 'Medium', 'Long', 'Very Long', 'Extremely Long'] .我正在尝试创建一个新的数据框,
这是我的数据框: email title id --------------------------------- balh@blah.com Title a
这是我的数据框: email title id --------------------------------- balh@blah.com Title a
目标 我正在尝试从 value_counts() 开始,为数据框中的每一列自动生成 EDA 报告。 问题 问题是我的函数没有返回任何内容。因此,虽然它确实打印到控制台,但它不会将相同的输出打印到我的文
我进行了一项调查,答案可以是 1-7,例如“绝对不快乐”到“绝对快乐”以及介于两者之间的一切,数据是一个 pandas 系列。对它进行 data.value_counts() 会产生有序表 5.0
我有一个在一组服务器上提出的票证的 pandas 数据框架,如下所示: a b c Users Problem 0 data data data U
自从我开始在 pandas 中使用categorical类型以来,我有一段无法工作的特定代码:(为了方便起见,我将其形成为测试): import pandas as pd import numpy a
我是一名优秀的程序员,十分优秀!