I don't know how to write Lambda in the argument with a new line.
I would like to write a code that behaves the same as the code below.
import pandas as pd
df = pd.DataFrame(
{
'name':('Hoge', 'Bar',
'value': ('1', '2')
}
)
conditionally_combine(r):
ifr ['name'] == 'Hoge':
return ['name'] + r ['value']
else:
return ['name']
df["combine"] = df.apply(lambdar:conditionally_combine(r),axis=1)
print(df)
https://naruport.com/blog/2019/9/5/python-tutorial-lambda/
The lambda formula is basically written in one line.
Therefore, multi-line lambda expressions are not supported.
If you want to write more than one line, escape a new line like ↓.
You cannot write a return statement like ↓ in the lambda formula.
Therefore, I did the following, but it is an error.
File line 11
ifr ['name'] == 'Hoge':
^
SyntaxError: invalid syntax
import pandas as pd
df = pd.DataFrame(
{
'name':('Hoge', 'Bar',
'value': ('1', '2')
}
)
df["combine"] = df.apply(lambdar:\
ifr ['name'] == 'Hoge':\
r['name']+r['value']\
else:\
r ['name']
,
axis = 1
)
print(df)
Also
http://www.sakito.com/2012/10/python-lambda.html
Here are some simple samples for now.Sometimes people think Lambda can't break a new line, but if you put it in parentheses, you can break a new line normally.
Therefore, I did the following, but the error was similar.
import pandas as pd
df = pd.DataFrame(
{
'name':('Hoge', 'Bar',
'value': ('1', '2')
}
)
df["combine"] = df.apply(lambdar:
ifr ['name'] == 'Hoge':
r['name'] + r['value']
else:
r ['name']
),
axis = 1
)
print(df)
if
is a statement as the comment states if
statement (statement).( if
appears in the middle of an expression is expression with a conditional expression)
(The relationship between the sentence and the expression is rather complicated, so I can't write everything down, so please refer to the following.)
In Python language reference, ...
You can write an expression in the expression section, which is summarized in this way and sometimes appears during the description of the statement, statement.In other words…
The following conditional decisions, such as the if
statement, can be considered as an expression.
Also Itertools, compress()
, filterfalse()
, dropwhile()
, takewheel()
etc. can be used?
Are there any other compress()
, filterfalse()
, dropwhile()
, takewhile()
, takewhile()
in itertools?
Also, if you use the function well, you may be able to do something in your own way.
import sys
lst = [print('hello'), print('world'), sys.exit(0)] Call by list/dict, etc.
Call by f'{func_a()}{func_b()}{sys.exit(0)}'#f-string
There is also a howto like this, so please refer to it
© 2024 OneMinuteCode. All rights reserved.