【发布时间】:2018-01-06 09:52:20
【问题描述】:
我有这个数据框:
df = pd.DataFrame([['137', 'earn'], ['158', 'earn'],['144', 'ship'],['111', 'trade'],['132', 'trade']], columns=['value', 'topic'] )
print(df)
value topic
0 137 earn
1 158 earn
2 144 ship
3 111 trade
4 132 trade
我想要一个额外的数字列,如下所示:
value topic topic_id
0 137 earn 0
1 158 earn 0
2 144 ship 1
3 111 trade 2
4 132 trade 2
所以基本上我想生成一个将字符串列编码为数值的列。我实现了这个解决方案:
topics_dict = {}
topics = np.unique(df['topic']).tolist()
for i in range(len(topics)):
topics_dict[topics[i]] = i
df['topic_id'] = [topics_dict[l] for l in df['topic']]
但是,我很确定有一种更优雅、更流行的方法来解决这个问题,但我在 Google 或 SO 上找不到任何东西。 我读到了 pandas 的 get_dummies 但这会为原始列中的每个不同值创建多个列。
感谢任何帮助或指示方向!
【问题讨论】: