Pandas DataFrame 应用函数将 DataFrame 的大小加倍
Pandas DataFrame apply function doubling size of DataFrame
我有一个包含数字数据的 Pandas DataFrame。对于每个非二进制列,我想识别大于其第 99 个百分位数的值,并创建一个布尔掩码,稍后我将使用它来删除具有异常值的行。
我正在尝试使用 apply
方法创建此布尔掩码,其中 df
是一个数据帧,其数字数据大小为 a*b,如下.
def make_mask(s):
if s.unique().shape[0] == 2: # If binary, return all-false mask
return pd.Series(np.zeros(s.shape[0]), dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)
s_bool = df.apply(make_mask, axis=1)
不幸的是,s_bool
输出为具有两倍列数的 DataFrame(即大小 a*(b *2)).前 b 列命名为 1、2、3 等,并且全是空值。第二个 b 列似乎是预期的掩码。
为什么 apply
方法将 DataFrame 的大小加倍? 不幸的是,Pandas apply documentation 没有提供有用的线索。
我不清楚为什么,但问题似乎是你返回的是一个系列。这似乎适用于您给出的示例:
def make_mask(s):
if s.unique().shape[0] == 2: # If binary, return all-false mask
return np.zeros(s.shape[0], dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)
你可以像这样进一步简化代码,使用raw=True
:
def make_mask(s):
if np.unique(s).size == 2: # If binary, return all-false mask
return np.zeros_like(s, dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)
我有一个包含数字数据的 Pandas DataFrame。对于每个非二进制列,我想识别大于其第 99 个百分位数的值,并创建一个布尔掩码,稍后我将使用它来删除具有异常值的行。
我正在尝试使用 apply
方法创建此布尔掩码,其中 df
是一个数据帧,其数字数据大小为 a*b,如下.
def make_mask(s):
if s.unique().shape[0] == 2: # If binary, return all-false mask
return pd.Series(np.zeros(s.shape[0]), dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)
s_bool = df.apply(make_mask, axis=1)
不幸的是,s_bool
输出为具有两倍列数的 DataFrame(即大小 a*(b *2)).前 b 列命名为 1、2、3 等,并且全是空值。第二个 b 列似乎是预期的掩码。
为什么 apply
方法将 DataFrame 的大小加倍? 不幸的是,Pandas apply documentation 没有提供有用的线索。
我不清楚为什么,但问题似乎是你返回的是一个系列。这似乎适用于您给出的示例:
def make_mask(s):
if s.unique().shape[0] == 2: # If binary, return all-false mask
return np.zeros(s.shape[0], dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)
你可以像这样进一步简化代码,使用raw=True
:
def make_mask(s):
if np.unique(s).size == 2: # If binary, return all-false mask
return np.zeros_like(s, dtype=bool)
else: # Otherwise, identify outliers
return s >= np.percentile(s, 99)