基于其他文本列向pandas dataframe添加数值列

2024-10-01 11:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个数据帧:

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,但这会为原始列中的每个不同值创建多个列。在

我很感谢你的帮助和指引!在


Tags: columns数据indataframedffortopicvalue
3条回答

选项1
pd.factorize

df['topic_id'] = pd.factorize(df.topic)[0]
df

  value  topic  topic_id
0   137   earn         0
1   158   earn         0
2   144   ship         1
3   111  trade         2
4   132  trade         2

选项2
np.unique

^{pr2}$

选项3
pd.Categorical

df['topic_id'] = pd.Categorical(df.topic).codes
df

  value  topic  topic_id
0   137   earn         0
1   158   earn         0
2   144   ship         1
3   111  trade         2
4   132  trade         2

选项4
dfGroupBy.ngroup

df['topic_id'] = df.groupby('topic').ngroup()
df

  value  topic  topic_id
0   137   earn         0
1   158   earn         0
2   144   ship         1
3   111  trade         2
4   132  trade         2

你可以用

In [63]: df['topic'].astype('category').cat.codes
Out[63]:
0    0
1    0
2    1
3    2
4    2
dtype: int8

我们可以使用apply函数在现有列的基础上创建新列,如下所示。在

topic_list = list(df["topic"].unique()) df['topic_id'] = df.apply(lambda row: topic_list.index(row["topic"]),axis=1)

相关问题 更多 >