简体   繁体   中英

python string replace conditional

I used a lot of stata but on my new job they won't shell out a license for me and excel is not enough to do a good job.

I want to know how to replace values in a column using a condition (a DataFrame in Pandas).

I've tried:

spot['tipo'] = np.where(['programa']=='CLASSIFICADOES' & ['espec']=='', 'N')

which gives me

TypeError: unsupported operand type(s) for &: 'str' and 'list'

and tried:

spot.ix('programa'=='CLASSIFICADOES' & ['espec']=='', 'tipo') = 'N'

Which gives me:

SyntaxError: can't assign to function call

and:

spot.replace(['tipo'],['N']) if spot['programa'] == 'CLASSIFICADOES' & ['espec']==''

Which is an invalid syntax. (and this one is much more alike what I would do on stata) I'm having loads of problems dealing with strings, the numeric parts i can usually find some solution on web.

In [79]: spot.dtypes
Out[79]: 
marca        object
data         object
rede         object
tipo         object
programa     object
titulo       object
valor       float64
cm            int64
col           int64
area          int64
descr        object
espec        object
dtype: object

What you tried has multiple errors:

spot['tipo'] = np.where(['programa']=='CLASSIFICADOES' & ['espec']=='', 'N')

should be:

spot['tipo'] = np.where((spot['programa']=='CLASSIFICADOES') & (spot['espec']==''), 'N', spot['tipo'])

notice the use of brackets which are required due to operator precedence and you need to index the df itself, what you compared was a list with a single entry which was a string.

spot.ix('programa'=='CLASSIFICADOES' & ['espec']=='', 'tipo') = 'N'

should be:

spot.ix[(spot['programa']=='CLASSIFICADOES') & (spot['espec']==''), 'tipo'] = 'N'

for the same reason as above

I think you should use something like this

Var= 'Yes' if fruit == 'Apple' else 'No'

In your case i don't fully understand your code, but i think meybe is like this.

spot['tipo'] = 'N' if (np.where(['programa']=='CLASSIFICADOES' & ['espec']=='')) else ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM