【问题标题】:Assign categorical mapping from one pd.Series to another将分类映射从一个 pd.Series 分配到另一个
【发布时间】:2019-01-22 08:08:32
【问题描述】:

我想将分类值的映射应用到从一个pd.Series 到另一个的代码。考虑一下这个 sn-p:

import pandas as pd

s1 = pd.Series(['a', 'b']).astype('category')
s2 = pd.Series(['b']).astype('category')

print(s1.cat.codes)
print(s2.cat.codes)

s2.cat.set_categories(s1.cat.categories)
print(s2.cat.codes)

我期望的输出是:

0    0
1    1
dtype: int8
0    0
dtype: int8
0    1
dtype: int8

因为在s1 'b' 被映射到1。但我得到的是:

0    0
1    1
dtype: int8
0    0
dtype: int8
0    0
dtype: int8

为什么? set_categories 操作什么也没做。似乎完全没有意义...

但是我如何实际上做到这一点?

(此外,我还需要将s1 中未出现的值(例如'c')映射为错误值,例如-1。)

【问题讨论】:

    标签: pandas mapping categories categorical-data


    【解决方案1】:

    您忘记将输出分配回s2

    s2 = s2.cat.set_categories(s1.cat.categories)
    print (s2)
    0    b
    dtype: category
    Categories (2, object): [a, b]
    
    print(s2.cat.codes)
    0    1
    dtype: int8
    

    【讨论】:

    • @lotolmencre - 在 pandas 中,只有极少数功能可以就地工作,例如 update,显然是必需的 inplace=True 参数,例如在reset_index.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多