2016-02-27 114 views
8

我的目標是比較兩列並添加結果列。 R使用ifelse,但我需要知道熊貓的方式。R/ifelse在Python/Pandas中的等價物?比較字符串列?

[R

> head(mau.payment) 
    log_month user_id install_month payment 
1 2013-06  1  2013-04  0 
2 2013-06  2  2013-04  0 
3 2013-06  3  2013-04 14994 

> mau.payment$user.type <-ifelse(mau.payment$install_month == mau.payment$log_month, "install", "existing") 
> head(mau.payment) 
    log_month user_id install_month payment user.type 
1 2013-06  1  2013-04  0 existing 
2 2013-06  2  2013-04  0 existing 
3 2013-06  3  2013-04 14994 existing 
4 2013-06  4  2013-04  0 existing 
5 2013-06  6  2013-04  0 existing 
6 2013-06  7  2013-04  0 existing 

熊貓

>>> maupayment 
user_id log_month install_month 
1  2013-06 2013-04    0 
     2013-07 2013-04    0 
2  2013-06 2013-04    0 
3  2013-06 2013-04   14994 

我嘗試了一些案件,但沒有奏效。看來字符串比較不起作用。

>>>np.where(maupayment['log_month'] == maupayment['install_month'], 'install', 'existing') 

TypeError: 'str' object cannot be interpreted as an integer 

請問您能幫我嗎?


熊貓和numpy版本。

>>> pd.version.version 
'0.16.2' 
>>> np.version.full_version 
'1.9.2' 

更新後版本,它的工作!

>>> np.where(maupayment['log_month'] == maupayment['install_month'], 'install', 'existing') 
array(['existing', 'install', 'existing', ..., 'install', 'install', 
     'install'], 
     dtype='<U8') 

回答

8

你必須升級大熊貓的最後一個版本,因爲在0.17.1版本,它工作得很好。

樣品(在install_month列第一值改變爲匹配):

print maupayment 
    log_month user_id install_month payment 
1 2013-06  1  2013-06  0 
2 2013-06  2  2013-04  0 
3 2013-06  3  2013-04 14994 

print np.where(maupayment['log_month'] == maupayment['install_month'], 'install', 'existing') 
['install' 'existing' 'existing']