python - 有没有一种简单的方法可以锁定熊猫数据框中的某些列不被操纵?
问题描述
我想对除需要保持不变的一对之外的每一列应用一个函数。我现在这样做的方式:
- 将 xxx 列分配给变量
- 从 df 中删除 xxx 列
- 对df做一些操作
- 将变量合并到 df
例子:
cobId = combined.Id
cobSale = combined.SalePrice
combined = combined.drop(['Id', 'SalePrice'], axis = 1)
combined=(combined-combined.mean())/combined.std()
combined['Id'] = cobId
combined['SalePrice'] = cobSale
这里如何改进?
解决方案
cols = combined.columns.difference(['Id','SalePrice'])
combined[cols] = combined[cols].sub(combined[cols].mean()).div(combined[cols].std())
print(combined)
这是一个例子:
df = pd.DataFrame({'col1':[1,2],'col2':[3,4]})
print(df)
col1 col2
0 1 3
1 2 4
cols = df.columns.difference(['col1'])
df[cols] = df[cols].sub(df[cols].mean()).div(df[cols].std())
print(df)
我们还可以使用DataFrame.update
:
df2=df.drop(axis=1,labels='col1')
#df2=df[df.columns.difference(['col1'])]
df2 = df2.sub(df2.mean()).div(df2.std())
df.update(df2)
print(df)
输出:
col1 col2
0 1 -0.707107
1 2 0.707107
推荐阅读
- excel - 如何修复模板excel格式的循环
- node.js - 带有路径重写的 Nginx 代理配置
- java - 如何使用 Thymeleaf 模板打印 HashMap 的 ArrayList 中的元素数?
- c# - Unity Shader 图形顶点位移不适用于运行时创建的网格
- node.js - 想要制作登录组件,但我的管理组件正在生效。就像导航栏正在进入该组件
- php - PHP 什么是静态关键字
- database - MongoDB - 从聚合查询中获取单个元素
- javascript - 如何在 botpress 自定义组件中获取 json 对象?
- angular - 使用 api 时以角度列出空列表
- kubernetes - 如何在 minikube 内运行的容器中获取 minikube ip 虚拟机地址