我在数据框中有这样的数据
文字 | 标签1 | Label2 | label3 | label4 | 标签 |
---|---|---|---|---|---|
你好,我叫约翰 | 1 | 0 | 1 | 0 |
我想根据一和零填充标签列,就像这样
文字 | 标签1 | Label2 | label3 | label4 | 标签 |
---|---|---|---|---|---|
你好,我叫约翰 | 1 | 0 | 1 | 0 | ['Label1','Label3'] |
我可以在 python 中做什么?
答案 0 :(得分:1)
好的,这是来自 this answer 的未经测试的建议。尝试收集适当的列标签,然后在适当的函数上使用 DataFrame.apply:
test_cols = [c for c in df.columns if c[:5].lower() == 'label']
test_cols.remove('Labels')
def aggLabels(aSeries):
return [lab for lab in test_cols if aSeries[lab]==1]
df['Labels'] = df.apply(aggLabels, axis=1)
正如我所说,这是未经测试的;可能需要调整代码。