Use np.where
Ex:
import numpy as np
df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])
Answer from Rakesh on Stack OverflowUse np.where
Ex:
import numpy as np
df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])
You can use pandas.DataFrame.loc:
df.loc[df["Target"] == 'U', "Target"] = df["Action"]
You can also use pandas.DataFrame.where
df["Target"].where(df["Target"] != 'U', df["Action"], inplace = True)
Note that in this case the cells that does NOT satisfy the condition are replaced, that's why you have to use != instead of ==.
python - replace item in a string if it matches an item in the list - Stack Overflow
python - how to replace if statements in a for loop (for better looking code) - Stack Overflow
Trying to replace input string with another string with multiple conditions
python string replace using for loop with if else - Stack Overflow
I like re module solutions
if not re.search(r'(?<!X)AAA', myString):
...
I don't want my script to notice any presence of
"XAAA"when it doesif 'AAA' not in myString.
You can first remove any occurrences of the sub-string XAAA from myString, and then test if AAA is not a sub-string of myString:
if 'AAA' not in myString.replace('XAAA', ''):
# do action
You are not keeping the result of x.replace(). Try the following instead:
for tag in tags:
x = x.replace(tag, '')
print x
Note that your approach matches any substring, and not just full words. For example, it would remove the LOL in RUN LOLA RUN.
One way to address this would be to enclose each tag in a pair of r'\b' strings, and look for the resulting regular expression. The r'\b' would only match at word boundaries:
for tag in tags:
x = re.sub(r'\b' + tag + r'\b', '', x)
The method str.replace() does not change the string in place -- strings are immutable in Python. You have to bind x to the new string returned by replace() in each iteration:
for tag in tags:
x = x.replace(tag, "")
Note that the if statement is redundant; str.replace() won't do anything if it doesn't find a match.
A defaultdict can be very helpful here. The defaultdict enables the creation of the specified dict-key-object (list) if it does not already exist, or uses the existing object's methods if it does exist.
On first iteration, the dict is empty, but the list.append method can be called on the 'empty' key, as the default object of the dict is a list. This SO post goes into greater detail.
For example:
from collections import defaultdict
sublist = ['green', 'red', 'red', 'red', 'blue', 'blue', 'green']
d = defaultdict(list)
for i in sublist:
d[i].append(i)
Output:
defaultdict(list,
{'green': ['green', 'green'],
'red': ['red', 'red', 'red'],
'blue': ['blue', 'blue']})
Which can be accessed just like a builtin dict:
>>> d['green']
['green', 'green']
Or, explicitly converted into a builtin dict:
>>> dict(d)
{'green': ['green', 'green'],
'red': ['red', 'red', 'red'],
'blue': ['blue', 'blue']}
Removing unwanted items
If the source list contains unwanted items, they can be removed as shown below.
The complete code:
from collections import defaultdict
sublist = ['green', 'red', 'red', 'red', 'blue', 'blue', 'green',
None, 'Sam', 'Bob', 'Sue', None, None]
# Append items to dict key/items.
d = defaultdict(list)
for i in sublist:
d[i].append(i)
# Define a list of items to be kept.
keep = ['blue', 'red', 'green']
# Iterate a *copy* of the dict and pop the unwanted items.
for k in d.copy():
if k not in keep:
d.pop(k)
Output:
defaultdict(list,
{'green': ['green', 'green'],
'red': ['red', 'red', 'red'],
'blue': ['blue', 'blue']})
You could do something like this? (untested)
colors = ['red', 'blue', 'green']
lists = {color: [] for color in colors}
for color, list_ in lists.items():
for item in sublist:
if color in sublist:
list_.append(item)
lists[color] = list(filter(None, list_).remove(color)
new = ['a ','local ','is ']
my_str = 'anindianaregreat'
old = ['an','indian','are']
for i, string in enumerate(old):
my_str = my_str.replace(string, new[i], 1)
print(my_str)
Your usage of range is incorrect.
range goes from lower (inclusive) to higher (exclusive) or simply 0 to higher (exclusive)
Your i == old condition is incorrect as well. (i is an integer, while old is a list). Also what is it supposed to do?
You can simply do:
for old_str, new_str in zip(old, new):
my_str = my_str.replace(old_str, new_str, 1)
https://docs.python.org/3/library/stdtypes.html#str.replace You can provide an argument to replace to specify how many occurrences to replace.
No conditional is required since if old_str is absent, nothing will be replaced anyway.
Here's how I would do it:
Just a couple notes first, you seem to have confused the syntax for dictionaries. Dictionaries start with { and end with }. [ and ] are used for lists and they don't have : (a list looks like: [1,2,3,4,5]. The following code will iterate through all the keys in the dictionary and then replace them properly in the string.
li={'20':'1','40':'2','60':'3','80':'4','100':'5'}
string='abcd abcd 60'
for key in li:
string = string.replace(key,li[key])
print(string)
a dictionary would probably be easier, so it would go something like this:
list={'20':'1','40':'2','60':'3','80':'4','100':'5'}
x='abcd abcd 60'
num = '60'
if num in x:
print('The new number is: '+list[num])
My question is answered, however feel free to add more if you'd like =)
I've been improving my Python recently and figured I could replace these "function trees" with a function dictionary
job.get_job()
if job.status == enums.Status.SUCCESS:
job.success()
elif job.status == enums.Status.NO_CONTENT:
job.no_content()
elif job.status == enums.Status.FAILURE:
job.failure()turns into
handler = dict() handler[enums.Status.SUCCESS] = job.success handler[enums.Status.NO_CONTENT] = job.no_content handler[enums.Status.FAILURE] = job.failure job.get_job() handler[job.status]()
In this case I don't need to pass any params, but when needed I use a lambda
It sure feels fancy, since this is new to me. But is it a good idea? Also open to other ideas.
The string replace method does not replace characters by position, it replaces them by what characters they are.
>>> 'apple aardvark'.replace('a', '!')
'!pple !!rdv!rk'
So in your first case, you are telling to replace "hk" with "kh". It doesn't "know" that you want to only replace one of the occurrences; it just knows you want to replace "hk" with "kh", so it replaces all occurrences.
You can use the count argument to replace to specify that you only want to replace the first occurrence:
>>> go = 'USC_45774-1111-0 <hkxhk> {10} ; 78'
... go.replace(go[22:24],go[23:21:-1],1)
'USC_45774-1111-0 <khxhk> {10} ; 78'
Note, though, that this will always replace the first occurrence, not necessarily the occurrence at the position in the string you specified. In this case I guess that's what you want, but it may not work directly for other similar tasks. (That is, there is no way to use this method as-is to replace the second occurrence or the third occurrence; you can only replace the first, or the first two, or the first three, etc. To replace the second or third occurrence you'd need to do a bit more.)
As for the second part of your question, you are misunderstanding what if "{01}" or "{-1}" in line means. It means, in layman's terms, if "{01}" or if "{-1}" in line. Since if "{01}" is always true (i.e., the string "{01}" is not a false value), the whole condition is always true. What you want is if "{01}" in line or "{-1}" in line".
I don't know what it is about Python, but your problem is one that gets posted here at least a couple times every day.
if "{01}" or "{-1}" in line:
This doesn't do what you think it does. It asks, "is "{01}" true"? Because it's a non-zero-length string, it is. Because or short-circuits, the rest of the condition is not tested because the first argument is true. Therefore the body of your if statement is always executed.
In other words, Python evaluates as if you'd written this:
if ("{01}") or ("{-1}" in line):
You want something like:
if "{01}" in line or "{-1}" in line:
Or if you have a lot of similar conditions:
if any(x in line for x in ("{01}", "{-1}")):