英文:
Python Convert column values of 1-50 to 1-10
问题
将一列中的值从1到50转换为1-10的最简单方法是将每个值除以5并向上取整,然后再加1。这将把1到50的范围映射到1到10的范围,如下所示:
[1, 2, 3, 4, 5] -> 1
[6, 7, 8, 9, 10] -> 2
[11, 12, 13, 14, 15] -> 3
...
[46, 47, 48, 49, 50] -> 10
英文:
I have values in a column that are 1 to 50. What is the easiest way to convert every 5 to scale back to 1-10? (e.g. [1,2,3,4,5] = 1, [6,7,8,9,10] = 2 )
答案1
得分: 1
输入对象不清楚,但您需要使用地板除法。
由于Python是从0开始计数,但您是从1开始计数,所以首先减去1,然后除以5,最后再加上1:
使用[numpy]示例:
import numpy as np
inpt = np.arange(1, 51)
out = (inpt-1)//5+1
输出:
array([ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4,
4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7,
7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10])
在纯Python中:
inpt = list(range(1, 51))
out = [(x-1)//5+1 for x in inpt]
在[pandas]中:
import pandas as pd
df = pd.DataFrame({'col': range(1, 51)})
df['out'] = df['col'].sub(1).floordiv(5).add(1)
英文:
The input object is unclear, but you need to use a floor division.
Since python counts from 0 but you from 1, first subtract 1, then divide, finally add 1 again:
Example with [tag:numpy]:
import numpy as np
inpt = np.arange(1, 51)
out = (inpt-1)//5+1
Output:
array([ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4,
4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7,
7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10])
In pure python:
inpt = list(range(1, 51))
out = [(x-1)//5+1 for x in inpt]
In [tag:pandas]:
import pandas as pd
df = pd.DataFrame({'col': range(1, 51)})
df['out'] = df['col'].sub(1).floordiv(5).add(1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论