我有这个数据帧:
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
我还需要一个类似这样的数字列:
^{pr2}$基本上,我想生成一个列的数值。我实施了这个解决方案:
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']]
不过,我很确定有一个更优雅和更通俗的方法来解决这个问题,但我在谷歌上找不到什么东西。 我读过pandas的get_dummies,但这会为原始列中的每个不同值创建多个列。在
我很感谢你的帮助和指引!在
选项1
pd.factorize
选项2
^{pr2}$np.unique
选项3
pd.Categorical
选项4
dfGroupBy.ngroup
你可以用
我们可以使用apply函数在现有列的基础上创建新列,如下所示。在
topic_list = list(df["topic"].unique()) df['topic_id'] = df.apply(lambda row: topic_list.index(row["topic"]),axis=1)
相关问题 更多 >
编程相关推荐