python - 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 值,我将无法合并回这些值。谢谢。
解决方案
所以我认为我通过不使用 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()
推荐阅读
- spring - Spring Cloud Config 服务器是否与 GitOps 兼容?
- java - 如何在数据库中正确实现验证注册?
- javascript - jQuery 产品显示页面不显示详细信息
- elasticsearch - ElasticSearch:如何从索引中删除所有具有特定值的特定字段的文档
- terraform - 以条件方式对动态块内容进行 Terraform
- c# - AndroidJavaException: java.lang.NoSuchMethodError: no non-static method with name='getStatusCode' signature='()I'
- css - 如何在 FireFox 上修复 transform-style:preserve-3d?
- javascript - 如何在 JavaScript 中创建自定义字母顺序?
- c - 找到平垫圈的面积和体积,我很困惑我的 C 程序是否正确。需要一些验证
- python - 是否可以在不安装搅拌机的情况下渲染 .blend 文件?