【问题标题】:Give weights to rows of dataframe赋予数据框行权重
【发布时间】:2021-10-04 21:18:33
【问题描述】:

我有一个用于不同来源(标记器)的数据库,我想为每个来源分配权重。

# source 1
df1 = pd.DataFrame({
      'feature': ['a', 'b', 'c'],
      'label': [1, 0, 0]
      })

# source 2
df2 = pd.DataFrame({
      'feature': ['d', 'e', 'f'],
      'label': [1, 0, 1]
      })

df = pd.concat([df1, df2]) # Here I want to assign distic weigths to df1 and df2

这样,当我训练模型时,模型会考虑特征的权重,即特征是否为 df1 与在 df2 中的特征在某种程度上不同(或多或少“重要”)。

clf = model()
X = df['feature']
y = df['label']
clf.fit(X, y, weight) # But here the weight is not the class_weight 
                      # but a weight in the feature

【问题讨论】:

  • 预期输出是什么?
  • pd.concat([df.assign(weight=i) for i,df in enumerate([df1,df2])] ) ?

标签: python pandas scikit-learn


【解决方案1】:

您可以assign 一个权重列,类似于@Quang 的建议,但具有定义的权重:

weights = [3, 4]
dfs = [df1, df2]
df = pd.concat([d.assign(weight=w) for w,d in zip(weights, dfs)])

输出:

  feature  label  weight
0       a      1       3
1       b      0       3
2       c      0       3
0       d      1       4
1       e      0       4
2       f      1       4

那么你应该可以做到:

clf = model()
X = df['feature']
y = df['label']
w = df['weight']
clf.fit(X, y, w)

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多