Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫重新映射到列中的范围_Python_Pandas_Numpy - Fatal编程技术网

Python 熊猫重新映射到列中的范围

Python 熊猫重新映射到列中的范围,python,pandas,numpy,Python,Pandas,Numpy,我有一个数据帧,其列id为:s,可以包含重复项: >>> 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

我有一个数据帧,其列id为:s,可以包含重复项:

>>> 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

这个问题有点令人困惑。。我不确定您是想将用户id增加任意数量,还是只想显示高于某个阈值的用户id。。。因此,我将给出这两个问题的解决方案:

df['user_id'].map(lambda x:x+2)将为您提供用户_id+2

loc[df['user\u id']>2]将只返回高于2的用户id

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

df['user_id'].排序_值()


希望有帮助

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
然后,您可以使用排序索引恢复索引:

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:s,以便它们从2开始,递增1。看看示例输出:)酷!如果我不关心索引或保存旧ID,那么只需要这么做,对吗?df1['user\u id']=pd.factorize(df1['user\u id'])[0]@user1506145确定或调用
reset\u index(drop=True)
重新开始索引