Inserting Random Values Based On Condition
I have the following DataFrame containing various information about a certain product. Input3 is a list of sentences created as shown below: sentence_list = (['Køb online her','Sa
Solution 1:
If you are guaranteed to have at least one item in Input3
that will satisfy this condition, you may want to try something like conditioning your random selection ONLY on values in your sentence_list
that would be of an acceptable length:
# convert to series to enable use of pandas filtering mechanism:
my_sentences = [s for s in sentence_list iflen(s) < MAX_LENGTH]
# randomly select from this filtered list:
np.random.choice(my_sentences)
In other words, perform the filter on each list of strings BEFORE you call random.choice
.
You can run this for each row in a dataframe like so:
defchoose_string(full_input):
return np.random.choice([
s
for s in sentence_list
iflen(s) + len(full_input) < 55
])
df["Input3_OK"] = df.Full_Input.map(choose_string)
Post a Comment for "Inserting Random Values Based On Condition"