【问题标题】:Change value column based on condition根据条件更改值列
【发布时间】:2017-03-30 14:19:51
【问题描述】:

我有一个数据框 df,其中有一列的值介于 0 和 1 之间。

我想将数值从数值更改为序数,如下所示:

'0-20'  for x <= 0.2
'20-40'  for 0.2 < x <= 0.4
'40-60'  for 0.4 < x <= 0.6
'60-80'  for 0.6 < x <= 0.8
'80-100'  for 0.8 < x <= 1
 I've passed X['Probability'].loc[X['Probability'] <= 0.2] = '0-20'

但是在下一个我得到一个错误说:

TypeError:不可排序的类型:str() > float()。

如何通过这个?谢谢!

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    你可以使用cut:

    bins = [-np.inf, .2, .4, .6, .8, 1]
    labels = ["{0} - {1}".format(i, i + 20) for i in range(0, 100, 20)]
    #same as
    #labels=['0-20','20-40','40-60','60-80','80-100']
    
    df['label'] = pd.cut(df['Probability'], bins=bins, labels=labels)
    

    示例:

    np.random.seed(100)
    df = pd.DataFrame(np.random.random((10,1)), columns=['Probability'])
    df.loc[0, 'Probability'] = 0
    df.loc[8, 'Probability'] = 0.4
    df.loc[9, 'Probability'] = 1
    
    bins = [-np.inf, .2, .4, .6, .8, 1]
    labels = ["{0} - {1}".format(i, i + 20) for i in range(0, 100, 20)]
    df['label'] = pd.cut(df['Probability'], bins=bins, labels=labels)
    print (df)
       Probability   label
    0     0.000000    0-20
    1     0.278369   20-40
    2     0.424518   40-60
    3     0.844776  80-100
    4     0.004719    0-20
    5     0.121569    0-20
    6     0.670749   60-80
    7     0.825853  80-100
    8     0.400000   20-40
    9     1.000000  80-100
    

    【讨论】:

    • 太棒了!等待冷却时间将其标记为答案。顺便说一句,如果值等于 0.4 会发生什么?会是 20-40 还是 40-60?
    • 等一下,我测试一下。
    猜你喜欢
    • 2022-11-30
    • 2013-12-27
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多