首页 > 解决方案 > For 循环遍历 Pandas DataFrame 中的所有列,Python 中的一(或两)列除外以进行缩放

问题描述

我正在转换我的数据框以执行 PCA 并将其拟合到无监督的 KMeans 聚类算法中。我希望保持我的目标/分类列不受影响。我真的不想分别对每一列执行操作,因此我想使用 for 循环。另外,我想继续拥有一个数据框而不是一个数组。这是我到目前为止所得到的:

# trim the outliers
for c in df:
    df[c] = df[df[c] < df[c].quantile(0.95)] # Remove top 5% of the values

# drop NaN 
df.dropna(inplace=True) 
df

# log transform each column while adding one to avoid -inf values
for c in df:
    df[c] = np.log10(df[c].values +1)

想象一下我不想转换的列称为 df['class'] 并且我不想将其删除,因为如果我在转换期间删除 NaN 值,我将无法合并回这些值。谢谢。

标签: pythonpandasloopsindexingtransformation

解决方案


所以我认为我通过不使用 for 循环而是使用 .iloc 解决了这个问题。并且还在删除 NaN 之前保存了我的专栏。

class_column = df_num['class'] # save the column class so it doesn't get transformed
df_trim = df_num.iloc[:, 1:12][df_num.iloc[:, 1:12] < df_num.iloc[:, 1:12].quantile(0.95)] # remove top 5% outliers or more if you want


# log transform all values and add one to avoid -inf values
for c in df_trim:
    df_trim[c]= np.log10(df_trim[c].values +1)
    
# recover class_column
df_trim['class'] = class_column

# drop NaN
features = df_trim.dropna()
features.head()

推荐阅读