Reputation: 1771
This question has certainly been asked in many forms before, however, I haven't been able to find one that incorporates multiple series inputs as well as a while loop. Hence my question:
Without the need for a for-loop ahead of the while loop, is it possible to output a series from this function:
def modify_to_100(first, second):
combined = first + second
while combined != 100:
combined += 1
return abs(combined)
I am passing multiple pandas series to the function. The series are always of the same length.
In [132]: first = pd.Series([50, 60, 40])
In [133]: second = pd.Series([20, 10, 40])
In [134]: modify_to_100(first,second)
The error I get - which is fairly descriptive and understandable. However, because each element of the Series will require a different number of loops, I am at loss as to the best way to handle this situation.
Out [134]: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I have tried a.all()
, as an example, and as expected this causes the loop to go forever. There will never be a time in which all() of the numbers will have 1 added to them and arrive to 100 at the same time.
The others a.empty(), a.bool(), a.item(), a.any()
don't seem to apply. Am I misperceiving one of these that might allow for each element of the series to progress individually?
So far everything that I have found suggests that a for-loop is necessary. I would like to avoid having to go row by row here.
Desired Output:
100, 100, 100
Any help, clarification, or efficient way to progress here would be much appreciated.
Upvotes: 2
Views: 595
Reputation: 13426
You are comparing a series with scalar value. combine is a series while 100 is a numeric value.
You can convert series into dataframe and pass into the function.
def modify_to_100(df):
df['new'] = df['first'] + df['second']
# df['new'] = np.where(df['new']!=100, 100, df['new'])
while True:
if all(df['new'].eq(100)):
break
df[df['new']<100] = df['new']+1
return df['new'].values
first = pd.Series([50, 60, 40])
second = pd.Series([20, 10, 40])
print(modify_to_100(pd.DataFrame({'first':first.values, 'second':second.values})))
Upvotes: 2
Reputation: 683
This error appears when you try to apply logical relations on a series. You can do this for an element of the series. So use a loop, extract an element from the series, and apply while
condition element-wise. Hope this helps!
Upvotes: 1