【发布时间】:2015-09-09 10:13:25
【问题描述】:
我正在尝试将 pandas DataFrame 对象转换为一个新对象,该对象包含基于一些简单阈值的点分类:
- 如果该点为
NaN,则值转换为0 - 如果该点为负数或 0,则值转换为
1 - 如果值超出基于整个列的特定条件,则转换为
2 - 否则值为
3
这是一个非常简单的独立示例:
import pandas as pd
import numpy as np
df=pd.DataFrame({'a':[np.nan,1000000,3,4,5,0,-7,9,10],'b':[2,3,-4,5,6,1000000,7,9,np.nan]})
print(df)
到目前为止创建的转换过程:
#Loop through and find points greater than the mean -- in this simple example, these are the 'outliers'
outliers = pd.DataFrame()
for datapoint in df.columns:
tempser = pd.DataFrame(df[datapoint][np.abs(df[datapoint]) > (df[datapoint].mean())])
outliers = pd.merge(outliers, tempser, right_index=True, left_index=True, how='outer')
outliers[outliers.isnull() == False] = 2
#Classify everything else as "3"
df[df > 0] = 3
#Classify negative and zero points as a "1"
df[df <= 0] = 1
#Update with the outliers
df.update(outliers)
#Everything else is a "0"
df.fillna(value=0, inplace=True)
导致:
我尝试使用.applymap() 和/或.groupby() 来加快进程,但没有成功。我在 this answer 中找到了一些指导,但是,当您不在 pandas 列中分组时,我仍然不确定 .groupby() 是否有用。
【问题讨论】:
标签: python numpy pandas outliers