Use of if/else in Dataframe.assign() results in ValueError: The truth value of a SeriesCheck if string is in a pandas dataframePandas data frame ValueError: The truth value of a Series is ambiguousDataFrame column comparison raises ValueError: The truth value of a Series is ambiguous.Python: If statement return ValueErrorValueError in pandas: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()pandas add columns ,note The truth value of a Series is ambiguousValueError (while creating a function in python): The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()Loop return error that the true value of the series is ambiguous
Why use [FormalN]?
Is a Senate trial required after the House impeaches a president?
Dicht antonym - what is it?
My mysterious "ruins" wander around and change on their own, what'd be a rational way for them to do that?
Does SQL Server Only Perform Calculations In A SELECT List Once?
What is my volume?
Does anyone know a basepoint-free construction of universal covers?
How does a Viper Antenna work?
What are standard cryptographic assumptions?
Does milk make your bones stronger?
50% portfolio in single stock, JPM - appropriate for 80 year old?
Why are Democrats mostly focused on increasing healthcare spending, rarely mentioning any proposals for decreasing the costs of healthcare services?
CO₂ level is high enough that it reduces cognitive ability. Isn't that a reason to worry?
Has Counterspell always been able to target any spell on the stack?
I have stack-exchanged through my undergrad math program. Am I likely to succeed in mathematics PhD programs?
Dissecting the exotic bulbfish
What DC should I use for someone trying to survive indefinitely solely with an alchemy jug as their only source of food and water? (survival campaign)
Total I/O cost of a process
How do the Martian rebels defeat Earth when they're grossly outnumbered and outgunned?
Identify the Eeveelutions
Why was the DC-9-80 so successful despite being obsolete almost from birth?
Was there a clearly identifiable "first computer" to use or demonstrate the use of virtual memory?
Grep over multiple files redirecting to a different filename each time
Which act of Congress authorized the Ukrainian aid which was allegedly withheld?
Use of if/else in Dataframe.assign() results in ValueError: The truth value of a Series
Check if string is in a pandas dataframePandas data frame ValueError: The truth value of a Series is ambiguousDataFrame column comparison raises ValueError: The truth value of a Series is ambiguous.Python: If statement return ValueErrorValueError in pandas: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()pandas add columns ,note The truth value of a Series is ambiguousValueError (while creating a function in python): The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()Loop return error that the true value of the series is ambiguous
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
I've got a ton of data transforms defined in a batch transform language that supports this structure: x = iif(condition, a, b). I want to rewrite these using dataframes.
I'm using Dataframe.assign() but get ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
df = pd.DataFrame(['apple', 'orange', 'granite'], columns=['name'])
df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-e9ad71ccc45b> in <module>()
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoreframe.py in assign(self, **kwargs)
3305 if PY36:
3306 for k, v in kwargs.items():
-> 3307 data[k] = com._apply_if_callable(v, data)
3308 else:
3309 # <= 3.5: do all calculations first...
~Anaconda3libsite-packagespandascorecommon.py in _apply_if_callable(maybe_callable, obj, **kwargs)
403
404 if callable(maybe_callable):
--> 405 return maybe_callable(obj, **kwargs)
406
407 return maybe_callable
<ipython-input-39-e9ad71ccc45b> in <lambda>(x)
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoregeneric.py in __nonzero__(self)
1571 raise ValueError("The truth value of a 0 is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
At first I thought this was due to a limitation of the keywords allowed in assign(), but a very similar construct works with apply():
df['name'].apply(lambda x: 'rocky' if (x=='granite') else 'yummy')
0 yummy
1 yummy
2 rocky
Name: name, dtype: object
However, this doesn't allow me use to an if-condition that uses multiple columns from the dataframe. Is there a way to get assign() to work?
python pandas dataframe
add a comment
|
I've got a ton of data transforms defined in a batch transform language that supports this structure: x = iif(condition, a, b). I want to rewrite these using dataframes.
I'm using Dataframe.assign() but get ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
df = pd.DataFrame(['apple', 'orange', 'granite'], columns=['name'])
df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-e9ad71ccc45b> in <module>()
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoreframe.py in assign(self, **kwargs)
3305 if PY36:
3306 for k, v in kwargs.items():
-> 3307 data[k] = com._apply_if_callable(v, data)
3308 else:
3309 # <= 3.5: do all calculations first...
~Anaconda3libsite-packagespandascorecommon.py in _apply_if_callable(maybe_callable, obj, **kwargs)
403
404 if callable(maybe_callable):
--> 405 return maybe_callable(obj, **kwargs)
406
407 return maybe_callable
<ipython-input-39-e9ad71ccc45b> in <lambda>(x)
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoregeneric.py in __nonzero__(self)
1571 raise ValueError("The truth value of a 0 is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
At first I thought this was due to a limitation of the keywords allowed in assign(), but a very similar construct works with apply():
df['name'].apply(lambda x: 'rocky' if (x=='granite') else 'yummy')
0 yummy
1 yummy
2 rocky
Name: name, dtype: object
However, this doesn't allow me use to an if-condition that uses multiple columns from the dataframe. Is there a way to get assign() to work?
python pandas dataframe
add a comment
|
I've got a ton of data transforms defined in a batch transform language that supports this structure: x = iif(condition, a, b). I want to rewrite these using dataframes.
I'm using Dataframe.assign() but get ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
df = pd.DataFrame(['apple', 'orange', 'granite'], columns=['name'])
df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-e9ad71ccc45b> in <module>()
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoreframe.py in assign(self, **kwargs)
3305 if PY36:
3306 for k, v in kwargs.items():
-> 3307 data[k] = com._apply_if_callable(v, data)
3308 else:
3309 # <= 3.5: do all calculations first...
~Anaconda3libsite-packagespandascorecommon.py in _apply_if_callable(maybe_callable, obj, **kwargs)
403
404 if callable(maybe_callable):
--> 405 return maybe_callable(obj, **kwargs)
406
407 return maybe_callable
<ipython-input-39-e9ad71ccc45b> in <lambda>(x)
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoregeneric.py in __nonzero__(self)
1571 raise ValueError("The truth value of a 0 is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
At first I thought this was due to a limitation of the keywords allowed in assign(), but a very similar construct works with apply():
df['name'].apply(lambda x: 'rocky' if (x=='granite') else 'yummy')
0 yummy
1 yummy
2 rocky
Name: name, dtype: object
However, this doesn't allow me use to an if-condition that uses multiple columns from the dataframe. Is there a way to get assign() to work?
python pandas dataframe
I've got a ton of data transforms defined in a batch transform language that supports this structure: x = iif(condition, a, b). I want to rewrite these using dataframes.
I'm using Dataframe.assign() but get ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
df = pd.DataFrame(['apple', 'orange', 'granite'], columns=['name'])
df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-e9ad71ccc45b> in <module>()
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoreframe.py in assign(self, **kwargs)
3305 if PY36:
3306 for k, v in kwargs.items():
-> 3307 data[k] = com._apply_if_callable(v, data)
3308 else:
3309 # <= 3.5: do all calculations first...
~Anaconda3libsite-packagespandascorecommon.py in _apply_if_callable(maybe_callable, obj, **kwargs)
403
404 if callable(maybe_callable):
--> 405 return maybe_callable(obj, **kwargs)
406
407 return maybe_callable
<ipython-input-39-e9ad71ccc45b> in <lambda>(x)
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')
~Anaconda3libsite-packagespandascoregeneric.py in __nonzero__(self)
1571 raise ValueError("The truth value of a 0 is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
At first I thought this was due to a limitation of the keywords allowed in assign(), but a very similar construct works with apply():
df['name'].apply(lambda x: 'rocky' if (x=='granite') else 'yummy')
0 yummy
1 yummy
2 rocky
Name: name, dtype: object
However, this doesn't allow me use to an if-condition that uses multiple columns from the dataframe. Is there a way to get assign() to work?
python pandas dataframe
python pandas dataframe
asked Mar 28 at 21:58
Scott WilsonScott Wilson
84 bronze badges
84 bronze badges
add a comment
|
add a comment
|
2 Answers
2
active
oldest
votes
When calling Series.apply
, the lambda receives each row value (i.e., a scalar value). With assign
, the lambda receives the entire DataFrame. Understanding this means you can now do something such as
df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or,
df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or, more simply, for in-place assignment,
df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df
name taste
0 apple y
1 orange y
2 granite r
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
add a comment
|
assign is not the function you should using with condition assignment
df['taste']=np.where(df['name'].eq('granite'),'rocky','yummy')
df
Out[513]:
name taste
0 apple yummy
1 orange yummy
2 granite rocky
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407474%2fuse-of-if-else-in-dataframe-assign-results-in-valueerror-the-truth-value-of-a%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
When calling Series.apply
, the lambda receives each row value (i.e., a scalar value). With assign
, the lambda receives the entire DataFrame. Understanding this means you can now do something such as
df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or,
df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or, more simply, for in-place assignment,
df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df
name taste
0 apple y
1 orange y
2 granite r
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
add a comment
|
When calling Series.apply
, the lambda receives each row value (i.e., a scalar value). With assign
, the lambda receives the entire DataFrame. Understanding this means you can now do something such as
df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or,
df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or, more simply, for in-place assignment,
df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df
name taste
0 apple y
1 orange y
2 granite r
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
add a comment
|
When calling Series.apply
, the lambda receives each row value (i.e., a scalar value). With assign
, the lambda receives the entire DataFrame. Understanding this means you can now do something such as
df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or,
df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or, more simply, for in-place assignment,
df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df
name taste
0 apple y
1 orange y
2 granite r
When calling Series.apply
, the lambda receives each row value (i.e., a scalar value). With assign
, the lambda receives the entire DataFrame. Understanding this means you can now do something such as
df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or,
df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r
Or, more simply, for in-place assignment,
df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df
name taste
0 apple y
1 orange y
2 granite r
answered Mar 28 at 22:06
cs95cs95
174k34 gold badges265 silver badges328 bronze badges
174k34 gold badges265 silver badges328 bronze badges
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
add a comment
|
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
Perfect! Thanks for the answer and the explanation of why apply() worked in the initial formulation.
– Scott Wilson
Mar 29 at 17:38
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
@ScottWilson awesome ... Please accept one of our answers if your question was solved. Click the grey check to the left of the answer to toggle it green. Thanks.
– cs95
Mar 29 at 17:55
add a comment
|
assign is not the function you should using with condition assignment
df['taste']=np.where(df['name'].eq('granite'),'rocky','yummy')
df
Out[513]:
name taste
0 apple yummy
1 orange yummy
2 granite rocky
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
add a comment
|
assign is not the function you should using with condition assignment
df['taste']=np.where(df['name'].eq('granite'),'rocky','yummy')
df
Out[513]:
name taste
0 apple yummy
1 orange yummy
2 granite rocky
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
add a comment
|
assign is not the function you should using with condition assignment
df['taste']=np.where(df['name'].eq('granite'),'rocky','yummy')
df
Out[513]:
name taste
0 apple yummy
1 orange yummy
2 granite rocky
assign is not the function you should using with condition assignment
df['taste']=np.where(df['name'].eq('granite'),'rocky','yummy')
df
Out[513]:
name taste
0 apple yummy
1 orange yummy
2 granite rocky
answered Mar 28 at 22:05
WeNYoBenWeNYoBen
166k10 gold badges59 silver badges95 bronze badges
166k10 gold badges59 silver badges95 bronze badges
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
add a comment
|
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
Thanks! The important point is to use np.where() in place of if/else. The answer below shows that assign() can be used too.
– Scott Wilson
Mar 29 at 17:40
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407474%2fuse-of-if-else-in-dataframe-assign-results-in-valueerror-the-truth-value-of-a%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown