![](/img/trans.png)
[英]How to perform an operation on specific columns within pandas dataframe while preserving other columns
[英]How to scale a few features of specific columns within pandas dataframe while preserving other columns?
I am doing it this way 1- dropping columns from the main dataframe which doesn't need feature scaling 2- now obtained dataframe only has columns that require feature scaling 3- concatenate the dropped out columns with the scaled columns to get the final dataframe
但
我想在不刪除任何列的情況下做到這一點。 使用將縮放前 14 列的命令購買,但其他列保留在 dataframe 我得到的 output
查看DataFrame.apply() 。 將軸參數設置為 1 將沿列應用 function。 您可以在 function 中放置一個過濾器,以僅包含您要縮放的列。
例如:
import pandas as pd
def scaling_function(x, col_to_scale):
for col in x.index:
if col in col_to_scale:
#your scaling operation here
x[col] = x[col] * 2
return x
df = pd.DataFrame([[4, 9, 2]] * 3, columns=['A', 'B', 'C'])
col_to_scale = ['A', 'B']
scaled_df = df.apply(lambda x: scaling_function(x, col_to_scale), axis=1)
將 A 列和 B 列中的值加倍,同時保持 C 不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.