gpt4 book ai didi

python - 如何基于数值变量创建分类变量

转载 作者:太空狗 更新时间:2023-10-30 00:27:46 25 4
gpt4 key购买 nike

我的 DataFrame 只有一列:

import pandas as pd
list=[1,1,4,5,6,6,30,20,80,90]
df=pd.DataFrame({'col1':list})

我如何再添加一个列“col2”,其中包含关于 col1 的分类信息:

if col1 > 0 and col1 <= 10 then col2 = 'xxx'
if col1 > 10 and col1 <= 50 then col2 = 'yyy'
if col1 > 50 then col2 = 'zzz'

最佳答案

你可以使用 pd.cut如下:

df['col2'] = pd.cut(df['col1'], bins=[0, 10, 50, float('Inf')], labels=['xxx', 'yyy', 'zzz'])

输出:

   col1 col2
0 1 xxx
1 1 xxx
2 4 xxx
3 5 xxx
4 6 xxx
5 6 xxx
6 30 yyy
7 20 yyy
8 80 zzz
9 90 zzz

关于python - 如何基于数值变量创建分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com