使用基于pandas中其他两列的条件创建列

时间:2018-05-28 11:07:29

标签: string pandas for-loop if-statement

我想根据其他两列的条件在pandas中创建一个列。我正在尝试使用带有if else条件的for循环,但在检查字符串值时遇到错误。

我的数据框:

df=pd.DataFrame({"Area:['USA','India','China','UK','France','Germany','USA','USA','India','Germany'],
         "Sales":[2,3,7,1,4,3,5,6,9,10]})

我想根据条件创建一个RATING列:

如果国家/地区位于ASIA且销售额> 2,则为1

如果国家/地区位于NA且销售额> 3,则为1

如果国家/地区为EUR且销售额> = 4,则为1 别的0

我正在使用一个功能:

ASIA=['India','China']
NA= ['USA']   
EUR=['UK','France','Germany']     
def label_race(row):
 if row['Area'].isin(ASIA) & row['Sales'] >2  :
   return 1
 if row['Area'].isin(NA) & row['Sales'] >3  :
   return 1  
 if row['Area'].isin(EUR) & row['Sales'] >=4  :
   return 1
 return 0  

df['Rating']=df.apply(lambda row: label_race(row),axis=1) 

引发以下错误:

AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')

请告诉我我在功能方面做错了什么,或者以其他方式更容易地做到这一点。

1 个答案:

答案 0 :(得分:3)

将矢量化解决方案与numpy.select

一起使用
m = [df['Area'].isin(ASIA) & (df['Sales'] > 2), 
     df['Area'].isin(NA) & (df['Sales'] > 3), 
     df['Area'].isin(EUR) & (df['Sales'] >= 4)]
df['Rating'] = np.select(m, [1,1,1], default=0)

print (df)
      Area  Sales  Rating
0      USA      2       0
1    India      3       1
2    China      7       1
3       UK      1       0
4   France      4       1
5  Germany      3       0
6      USA      5       1
7      USA      6       1
8    India      9       1
9  Germany     10       1

您的解决方案应该改为inand而不是isin&

def label_race(row):
 if row['Area'] in (ASIA) and row['Sales'] >2  :
   return 1
 if row['Area'] in (NA) and row['Sales'] >3  :
   return 1  
 if row['Area'] in (EUR) and row['Sales'] >=4  :
   return 1
 return 0  

df['Rating']=df.apply(lambda row: label_race(row),axis=1) 
print (df)
      Area  Sales  Rating
0      USA      2       0
1    India      3       1
2    China      7       1
3       UK      1       0
4   France      4       1
5  Germany      3       0
6      USA      5       1
7      USA      6       1
8    India      9       1
9  Germany     10       1

差异在于绩效:

#[10000 rows x 3 columns]
df = pd.concat([df] * 1000, ignore_index=True)

In [216]: %timeit df['Rating1']=df.apply(lambda row: label_race(row),axis=1)
275 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [217]: %timeit df['Rating'] = np.select(m, [1,1,1], default=0)
215 µs ± 3.46 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

我尝试从评论中检查@Anton vBR的想法:

def label_race(row):
 if row['Area'] in (ASIA) and row['Sales'] >2  :
   return 1
 elif row['Area'] in (NA) and row['Sales'] >3  :
   return 1  
 elif row['Area'] in (EUR) and row['Sales'] >=4  :
   return 1
 else:
   return 0  

df['Rating1']=df.apply(lambda row: label_race(row),axis=1) 

In [223]: %timeit df['Rating1']=df.apply(lambda row: label_race(row),axis=1)
268 ms ± 2.43 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
相关问题