pandas .drop()和.filter()在运行Python函数(def)时不起作用

uhry853o  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(134)

当我尝试在Python中的dataframe上运行函数(def)时,**df.drop()df.filter()**不起作用,它只返回原始的dataframe。你能告诉我缺少的魔力在哪里吗?提前告诉我。我已经尝试了.drop()的不同变体,但它们都不起作用。

示例:

def standard_f(dset):
 scaler = StandardScaler()for i in dset.columns:dset[i+"_std"]
 scaler.fit_transform(dset[i].to_numpy().reshape(-1,1))
 return dset

standard_f(df.drop(["customer_id"], axis=1))
0g0grzrc

0g0grzrc1#

下面是如何执行此操作的示例:

from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np

np.random.seed(123)
data = np.random.randn(5, 4)
df = pd.DataFrame(data, columns=['A', 'B', 'C', 'D'])
df['customer_id'] = ['C1', 'C2', 'C3', 'C4', 'C5']

df.head()
def standard_f(dset):
    scaler = StandardScaler()
    for i in dset.columns:
        dset[i+"_std"] = scaler.fit_transform(dset[i].to_numpy().reshape(-1,1))
    return dset.drop(columns=dset.columns[:-len(dset.columns)//2], axis=1)

df_transformed = standard_f(df.drop(["customer_id"], axis=1))
print(df_transformed)

返回df

A         B         C         D customer_id
0 -1.085631  0.997345  0.282978 -1.506295          C1
1 -0.578600  1.651437 -2.426679 -0.428913          C2
2  1.265936 -0.866740 -0.678886 -0.094709          C3
3  1.491390 -0.638902 -0.443982 -0.434351          C4
4  2.205930  2.186786  1.004054  0.386186          C5

对于变形的:

A_std     B_std     C_std     D_std
0 -1.377340  0.271539  0.639613 -1.752797
1 -0.977238  0.807545 -1.716846 -0.021368
2  0.478304 -1.256018 -0.196875  0.515721
3  0.656212 -1.069312  0.007410 -0.030109
4  1.220062  1.246246  1.266697  1.288554

相关问题