python - 丢弃方差为零的组
问题描述
假设下一个df:
d={'month': ['01/01/2020', '01/02/2020', '01/03/2020', '01/01/2020', '01/02/2020', '01/03/2020'],
'country': ['Japan', 'Japan', 'Japan', 'Poland', 'Poland', 'Poland'],
'level':['A01', 'A01', 'A01', 'A00','A00', 'A00'],
'job title':['Insights Manager', 'Insights Manager', 'Insights Manager', 'Sales Director', 'Sales Director', 'Sales Director'],
'number':[0, 0.001, 0, 0, 0, np.nan],
'age':[24, 22, 45, np.nan, 60, 32]}
df=pd.DataFrame(d)
这个想法是按组(在本例中为: 和 )获取特定列的方差country
,level
然后job title
选择方差低于某个阈值的段并将它们从原始 df 中删除。
但是应用时:
# define variance threshold
threshold = 0.0000000001
# get the variance by group for specific column
group_vars=df.groupby(['country', 'level', 'job title']).var()['number']
# select the rows to drop
rows_to_drop = df[group_vars<threshold].index
# drop the rows in place
#df.drop(rows_to_drop, axis=0, inplace=True)
出现下一个错误:
ValueError:缓冲区 dtype 不匹配,预期为“Python 对象”但得到“长长”
预期的数据框会下降:Poland A00 Sales Director 0.000000e+00
对于所有月份,因为它是一个零方差的段。
是否可以重新索引group_vars
以将其从原始 df 中删除?
我错过了什么?
解决方案
您可以通过转换实现此目的
# define variance threshold
threshold = 0.0000000001
# get the variance by group for specific column
group_vars=df.groupby(['country', 'level', 'job title'])['number'].transform('var')
# select the rows to drop
rows_to_drop = df[group_vars<threshold].index
# drop the rows in place
df.drop(rows_to_drop, axis=0, inplace=True)
这使:
month country level job title number age
0 01/01/2020 Japan A01 Insights Manager 0.000 24.0
1 01/02/2020 Japan A01 Insights Manager 0.001 22.0
2 01/03/2020 Japan A01 Insights Manager 0.000 45.0
推荐阅读
- javascript - Apex Oracle - 多个动态操作
- css - HTML/CSS 排列 div
- reactjs - 未处理的拒绝 -SyntaxError - JSON 输入的意外结束
- python - 从 Collada (.dae) 文件(在 Maya 中创建)导入的 SceneKit 键控混合形状动画未播放
- python - 在 Python 中重复打印多行
- websocket - 使用 http-kit 和 Clojure 处理“房间”
- javascript - 需要帮助来抓取网站
- sqlite - 设置 Amazon Web Services (AWS) 数据库和 EC2
- vb.net - VB.Net中DataGridView数据的下一个序列号
- javascript - 如何从 HTML 元素中删除属性