【问题标题】:Filter Pandas Dataframe only with Float32 dtype [duplicate]仅使用 Float32 dtype 过滤 Pandas Dataframe [重复]
【发布时间】:2019-10-07 07:23:27
【问题描述】:

我有这种方法,我只需要将其应用于'float32' 的列而不是所有列。

def preprocess(self, dataframe):
    if self._means is None: 
      self._means = np.mean(dataframe, axis=0)

    if self._stds is None:
      self._stds = np.std(dataframe, axis=0)
      if not self._stds.all():
        raise ValueError('At least one column has std deviation of 0.')

    return (dataframe - self._means) / self._stds

我收集这样的类型,但正在寻找 Pythonic 的方式来做到这一点:

dtypes = list(zip(dataframe.dtypes.index, map(str, dataframe.dtypes)))
# Normalize numeric columns.
 for column, dtype in dtypes:
    if dtype == 'float32':

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以像这样创建一系列 float32 类型的列:

cols = dataframe.columns[dataframe.dtypes == 'float32']

然后将它们传递给您的函数:

dataframe[cols].apply(preprocess)

【讨论】:

    【解决方案2】:

    pandas 方法将首先提取数字 columnsselect_dtypes

    subdf= df.select_dtypes(include='float32') 
    subdf=subdf.apply(preprocess,axis=1)
    df[list(subdf)]=subdf 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2014-02-06
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 2015-12-13
      • 2018-01-02
      相关资源
      最近更新 更多