【问题标题】:Pandas remap to range in column熊猫重新映射到列中的范围
【发布时间】:2017-01-23 22:53:38
【问题描述】:

我有一个带有 id:s 列的 DataFrame,可以包含重复项:

>>> df['user_id'].head()
Out[3]: 
0    2134
1    1234
2    4323
3    25434
4    1234
Name: user_id, dtype: int64

如何重新映射它,以便用户 ID 从任意数字开始,并根据原始数字递增?在此示例中,它将是以下内容,从 2 开始:

>>> df['user_id'].head()
Out[3]: 
0    3
1    2
2    4
3    5
4    2
Name: user_id, dtype: int64

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    IIUC,您想先按该列中的值对 df 进行排序,然后使用factorize

    In [29]:
    df1 = df.reindex(df['user_id'].sort_values().index)
    df1
    
    Out[29]:
           user_id
    index         
    1         1234
    4         1234
    0         2134
    2         4323
    3        25434
    
    In [30]:    
    df1['new_id'] = pd.factorize(df1['user_id'])[0] + 2
    df1
    
    Out[30]:
           user_id  new_id
    index                 
    1         1234       2
    4         1234       2
    0         2134       3
    2         4323       4
    3        25434       5
    

    然后您可以使用sort_index 恢复索引:

    In [31]:
    df1 = df1.sort_index()
    df1
    
    Out[31]:
           user_id  new_id
    index                 
    0         2134       3
    1         1234       2
    2         4323       4
    3        25434       5
    4         1234       2
    

    然后您可以覆盖或删除一列,以上只是为了演示如何获取您想要的值

    【讨论】:

    • 酷!如果我不关心索引或保存旧的 id,这只是为了做到这一点,对吧? df1['user_id'] = pd.factorize(df1['user_id'])[0]
    • @user1506145 确定或致电reset_index(drop=True) 让索引从0 重新开始
    【解决方案2】:

    这个问题有点令人困惑..我不确定您是否想将用户 ID 增加任意数字,或者您是否只想显示高于某个阈值的用户 ID...所以我会给出一个解决方案两者:

    df['user_id'].map(lambda x: x+2) 会给你 user_ids +2

    df.loc[df['user_id']>2] 只会返回大于 2 的 user_ids

    如果您想对用户 ID 进行排序,您可以:

    df['user_id'].sort_values()

    希望有帮助!

    【讨论】:

    • 谢谢,但也没有。我想重新映射用户 id:s,以便它们从 2 开始并以 1 递增。查看示例输出:)
    猜你喜欢
    • 2018-07-23
    • 2018-10-10
    • 1970-01-01
    • 2019-07-12
    • 2021-05-03
    • 2022-01-06
    • 2021-05-03
    • 2019-01-02
    • 2020-07-07
    相关资源
    最近更新 更多