如何将一系列数值数据转换为特定的分类数据?

时间:2019-10-21 08:24:45

标签: python pandas

我在此范围内的数据处于从-100到100的负数浮动范围,我想通过以下方式更改此数据:

from 0 to 1 - ss
from 1 to 2 - sm
from 2 to 3 - sa
> 3 s

from 0 to -1 - bs
from 1 to -2 - bm
from 2 to -3 - ba
< 3 b

该怎么办?

谢谢

1 个答案:

答案 0 :(得分:1)

请检查以下解决方案:

import pandas as pd

y = pd.DataFrame({"Data": [1.1, 1.3, 2.5, 3.9, -0.7, -1.3, -2.6, -9]})


def change_func(x):
    if x <= -3:
        return "b"
    elif -3 < x <= -2:
        return "ba"
    elif -2 < x <= -1:
        return "bm"
    elif -1 < x <= 0:
        return "bs"
    elif 0 < x <= 1:
        return "ss"
    elif 1 < x <= 2:
        return "sm"
    elif 2 < x <= 3:
        return "sa"
    else:
        return "s"


y["New_Column"] = y["Data"].apply(lambda x: change_func(x))

# if you do not want new line you can do the following:
# instead of y["New_Column"] = y["Data"].apply(lambda x: change_func(x) let's do:
# y["Data"] = y["Data"].apply(lambda x: change_func(x))

print(y)

我希望这会有所帮助,让我知道问题是否解决,随时提出问题。