简体   繁体   English

python字符串替换条件

[英]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. 我花了很多时间,但在我的新工作上,他们不会为我掏出许可证,而excel不足以做好工作。

I want to know how to replace values in a column using a condition (a DataFrame in Pandas). 我想知道如何使用条件(Pandas中的DataFrame)替换列中的值。

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. (这与我在stata上做的事情非常相似)我在处理字符串(通常可以在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. 注意,由于运算符的优先级而需要使用方括号,并且您需要索引df本身,您比较的是带有单个条目的列表,该条目是一个字符串。

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. 在您的情况下,我无法完全理解您的代码,但是我认为meybe就是这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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