我有四个表:predicted_tags、actual_tags、tags_names 和 news_text。
在表 predicted_tags 和 actual_tags 中,行名称是标签 ID。在这些表中,1 表示 True,0 表示 False。
predicted_tags 和 actual_tags 的形状是 (23413, 1369)。
predicted_tags:
print(predicted_tags)
+-------+-----+---+-----+------+------+
| | 1 | 3 | ... | 8345 | 8347 |
+-------+-----+---+-----+------+------+
| 35615 | 0 | 0 | ... | 1 | 0 |
| 58666 | 1 | 0 | ... | 0 | 0 |
| 16197 | 0 | 0 | ... | 0 | 1 |
| 68824 | 0 | 0 | ... | 1 | 1 |
| 22277 | 0 | 0 | ... | 1 | 0 |
+-------+-----+---+-----+------+------+
实际标签:
print(actual_tags)
+-------+-----+---+-----+------+------+
| | 1 | 3 | ... | 8345 | 8347 |
+-------+-----+---+-----+------+------+
| 35615 | 0 | 0 | ... | 1 | 0 |
| 58666 | 1 | 1 | ... | 0 | 0 |
| 16197 | 0 | 0 | ... | 0 | 1 |
| 68824 | 0 | 0 | ... | 1 | 1 |
| 22277 | 0 | 1 | ... | 1 | 0 |
+-------+-----+---+-----+------+------+
tags_names:
print(tags_names)
+--------+----------+-------------+
| | tag_id | tag_name |
+--------+----------+-------------+
| 127579 | 1 | politics |
| 108814 | 3 | economics |
| ... | ... | ... |
| 18 | 8345 | hot |
| 257141 | 8347 | environment |
+--------+----------+-------------+
新闻文本:
print(news_text)
+----------+------------------------+-----------------------------+
| | news_name | news_content |
+----------+------------------------+-----------------------------+
| 35615 | Secret of… | Hi! Today I will talk... |
| 58666 | Conversations with a … | I have a big experience... |
| 16197 | Harm of alcohol | Today, we… |
| ... | ... | ... |
| 68824 | Hot news | Celebrity with... |
| 22277 | Finance market | Last week… |
+----------+------------------------+-----------------------------+
我要获取下一张表:
+-------+------------------------+----------------------------+------------------------+---------------------------+
| | news_name | news_content | predicted_tags | actual_tags |
+-------+------------------------+----------------------------+------------------------+---------------------------+
| 35615 | Secret of… | Hi! Today I will talk... | ['hot'] | ['hot'] |
| 58666 | Conversations with a … | I have a big experience... | ['politics'] | ['politics', 'economics'] |
| 16197 | Harm of alcohol | Today, we… | ['environment'] | ['environment'] |
| 68824 | Hot news | Celebrity with... | ['hot', 'environment'] | ['hot', 'environment'] |
| 22277 | Finance market | Last week… | ['hot'] | ['hot', 'economics'] |
+-------+------------------------+----------------------------+------------------------+---------------------------+
我如何使用 Pandas 执行此操作?
请您参考如下方法:
将tags_names df 转换成字典并用它来重命名列:
tag_names = dict(zip(tags_names['tag_id'], tags_names['tag_names']))
predicted_tags.rename(columns = tag_names, inplace = True)
actual_tags.rename(columns = tag_names, inplace = True)
获取值为1的列名。
news_text['actual_tags'] = (actual_tags == 1 ).apply(lambda y: actual_tags.columns[y.tolist()].tolist(), axis=1)
news_text['predicted_tags'] = (predicted_tags == 1 ).apply(lambda y: predicted_tags.columns[y.tolist()].tolist(), axis=1)
