首页 > 解决方案 > python中的段/分析

问题描述

请帮忙!!

我试图根据条件创建一个列“段”:

 if 'Pro_vol' >1 and 'Cost' >=43 then append 1 
 if 'Pro_vol' ==1 and 'Cost' >=33 then append 1 
 or append 0

下面是数据的代码:

df = pd.DataFrame({'ID':[1,2,3,4,5,6,7,8,9,10],
            'Pro_vol':[1,2,3,1,5,1,2,1,4,5],
              'Cost' : [12.34,13.55,34.00, 19.15,13.22,22.34,33.55,44.00, 29.15,53.22]})

我尝试了一个代码:

Segment=[]

for i in df['Pro_vol']:
if i >1:
    Segment.append(1)
    for j in df['Cost']:
        if j>=43:
            Segment.append(1)
elif i==1:
    Segment.append(1)
elif j>=33:
    Segment.append(1)
else:
    Segment.append(0)

df['Segment']=Segment

它给了我一个错误:

ValueError: Length of values does not match length of index

我不知道任何其他方法可以尝试找到答案!

标签: python-3.xpandas

解决方案


你可以考虑np.where

np.where(((df.Cost>=33)&(df.Pro_vol==1))|((df.Cost>=43)&(df.Pro_vol>1)),1,0)
Out[538]: array([0, 0, 0, 0, 0, 0, 0, 1, 0, 1])

推荐阅读