【问题标题】:Columns in Pandas Dataframe [duplicate]Pandas Dataframe 中的列 [重复]
【发布时间】:2019-11-26 23:28:18
【问题描述】:

我有一个汽车数据框。我有它的汽车价格列,我想创建一个新列汽车范围,根据汽车价格具有“高”、“低”等值。比如:

如果价格在 0 到 9000 之间,那么这些汽车的续航里程应该为“低”。同样,如果价格在 9000 到 30,000 辆之间,那么这些汽车的范围应该是“中等”等。我尝试这样做,但我的代码正在将一个值替换为另一个值。有什么帮助吗?

我在价格列中运行了一个 for 循环,并使用 if-else 迭代来定义我的列值。

for i in cars_data['price']:
    if (i>0 and i<9000): cars_data['carsrange']='Low'
    elif (i<9000 and i<18000): cars_data['carsrange']='Medium-Low'
    elif (i<18000 and i>27000): cars_data['carsrange']='Medium'
    elif(i>27000 and i<36000): cars_data['carsrange']='High-Medium'
    else : cars_data['carsrange']='High'

现在,当我运行汽车范围的独特功能时,它只显示“高”。 汽车数据['carsrange'].unique()

这是输出:

在[74]:cars_data['carsrange'].unique() Out[74]: array(['High'], dtype=object)

我相信我在这里应用了错误的概念。关于我现在应该做什么的任何想法?

【问题讨论】:

    标签: python pandas spyder


    【解决方案1】:

    你可以使用列表:

    resultList = []
    for i in cars_data['price']:
        if (i>0 and i<9000): 
            resultList.append("Low")
        else:
            resultList.append("HIGH")
            # write other conditions here
    
    cars_data["carsrange"] = resultList
    

    然后从 cars_data["carsrange"] 中查找 uinque 值

    【讨论】:

    • 欢迎,如果这个答案解决了你的问题,请接受它作为正确答案
    猜你喜欢
    • 2014-07-08
    • 2020-08-02
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2015-12-13
    • 2018-01-02
    • 2014-01-19
    相关资源
    最近更新 更多