我不确定如何针对特定的列集自动执行它。
它将进入特定列,检查值。如果一个值等于或大于 10,它将替换为 100,如果小于 100,它将替换为 0。但是它会对所有列执行此操作,而不是每次都指定列的名称。
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000,
n_features=6,
n_informative=3,
n_classes=2,
random_state=0,
scale = 10,
shuffle=False)
# Creating a dataFrame
df = pd.DataFrame({'car':X[:,0],
'ball':X[:,1],
'Feature 3': 5,
'Feature 4':X[:,3],
'Feature 5':X[:,4],
'Feature 6':X[:,5],
'Class':y})
df.loc[df['Feature 6'] > 10, 'Feature 6'] = 100
并且将使用以下行提取列集
spike_cols = [col for col in df.columns if "tu" in str(col)]
所以基本上更改列名称中任何位置包含 tu 的列的值
请您参考如下方法:
我想你需要numpy.where使用 DataFrame 构造函数,因为它返回一个 2d numpy 数组:
df = pd.DataFrame(np.where(df >= 10, 100, 0), columns=df.columns, index=df.index)
感谢 @Wen 提供 DataFrame.ge 的解决方案和 100 的多个 bool 掩码,True 是像 1 和 False 像 0:
df = df.ge(10).mul(100)
编辑:如果只想为某些列应用解决方案:
df[spike_cols] = pd.DataFrame(np.where(df[spike_cols] >= 10, 100, 0),
columns=spike_cols, index=df.index)
df[spike_cols] = df[spike_cols].ge(10).mul(100)
