NFTs: Why Investing In NFTs Is A Good Move?

OverView Of NFTs

In short, NFT is a physical/digital asset that represents real world entities like images, audio tracks, gifs, gaming assets, arts, or any other real world objects. An NFT owner can retain the copyright of their assets and thereby can earn a percentage of revenue whenever their NFT is exchanged to another third person.

Pros Of Investing In NFTs

Did you know?
Investors, gamers and artists are rushing to invest in NFTs!
Are you one of them?
Then this blog is worth it, if you spare your time by checking out the benefits of investing in NFTs.

1. Immutability
NFTs are stored on the blockchain network and holds the entire record of transaction history on top of a blockchain ledger. Such data in the blockchain is immutable and could not be tampered at any cost.

Investors who are ready to invest in NFTs can create a secured network where each and every minute detail in blockchain is completely safe and immutable.

2. Proof Of Ownership & Fractionalised Ownership
NFT ownership is held by only a single ledger which means there is only one owner who actually possesses the ownership of the assets. However NFTs can be fractionalized into several assets by breaking it into multiple NFTs. Fractional owners take control of those divided NFTs whereas the actual ownership is still in control of the first owner.

3. Fractional Buying  
NFTs create more opportunities by dividing tangible assets into multiple ones. It is challenging to divide those assets, but NFTs overcome those struggles by dividing NFTs into multiple fractions to promote fractional buying.

Now it becomes simpler to distribute NFTs to their fans who are ready to buy. Further it strengthens the NFT community among their numerous rivals. It also fosters the liquidity rate by expanding the market cap, increases the value of the assets, etc.

4. Nurtures A Community
Investors take the first initial step to build a community for the NFT freaks. Once the platform is one live, several NFT freaks join the community and initiate activities like NFT exchanges, acquiring royalties,  etc. Even there is a great possibility for you to become famous in the future.

5. Efficiency
Smart contracts in NFTs are smart enough to initiate a transaction is the quickest way. It’s absolutely safe as the transactions are self-executed based on the pre-defined set of programmed codes. On the other hand, it minimises errors and risks to a great extent.

6. Portfolio Diversification
Investors can show many projects in their portfolio as they can diversify their investment portfolio into many. If an investor creates an NFT collectible then they can mention it as their NFT collectible and physical asset exclusively developed for arts, music, etc.

7. Potential Growth
Similar to share markets and investing in stocks, NFTs too have the capability to increase their value in the future. Potential growth in NFTs is limitless and endless than you could think of.  

Closing Thoughts

NFTs are apparently expected to rule our future in various domains like real estate, art galleries, musical industry, gaming market, etc. As of now, it captivates a big record of profits with users in millions and billions. Holding an astonishing record, there is always a positive effect in investing on NFTs. If you are one such individual who likes to be famous in this trending industry then never fail to consult a professional at NFT Development Company.

Assetfinx - An industry leader in creating NFTs, has a strong team who can deliver A-Z solutions on projects like NFT marketplace, NFT Games, NFTs for arts, NFTs for music, NFTs for real estate, etc. Get quick consultation with our tech team instantly to get started.

Get Detailed Guide: Pros Of Investing In NFTs
Phone/ Whatsapp: 638 430 1100
Mail: contact@assetfinx.net
 

What is GEEK

Buddha Community

NFTs: Why Investing In NFTs Is A Good Move?
steve joseph

steve joseph

1654674298

Top new cryptocurrencies to invest in June – 2022

June – is the month of new beginnings, and what better way to start off fresh than by investing in one (or more) of the many new cryptocurrencies that have recently hit the market? In this article, we’ll give you our top picks for the best cryptocurrencies to invest in for June of 2022.

Solana:

  1. Solana is a new cryptocurrency that is quickly gaining popularity. It is based on the Ethereum blockchain and utilizes Proof of Stake (PoS) to validate transactions. This makes it more energy-efficient than other PoW-based currencies.
  2. Solana has a very fast transaction speed. It can handle up to 65,000 transactions per second. This is much faster than Ethereum, which can only handle around 15 transactions per second.
  3. Solana has a strong team of developers behind it. The team includes former employees of Google, Facebook, and PayPal.
  4. Solana is already being used by some major companies, such as Coinbase and Binance.

Overall, Solana is a very promising new cryptocurrency. Its fast transaction speed, strong team of developers, and major company partnerships make it a good choice for investors looking for a new currency to invest in.

Hashpe:

Hashpe is a new cryptocurrency that was created in June of this year. It is based on the Bitcoin protocol, but it has some unique features that make it different from Bitcoin.

For one, Hashpe uses a different mining algorithm than Bitcoin. This means that it is more resistant to ASIC miners, which are specialized hardware that is designed for mining Bitcoin. This makes Hashpe more accessible to regular people who want to mine cryptocurrency.

Hashpe also has a built-in privacy feature called “zk-SNARKs.” This allows transactions on the Hashpe network to be private and secure.

Overall, Hashpe is a promising new cryptocurrency with some unique features that make it worth investing in.

Shiba Inu:

Shiba Inu is a new cryptocurrency that was created in August 2020. It is an Ethereum token that was created as a parody of the popular Dogecoin. However, Shiba Inu has quickly gained popularity in its own right and is now one of the top 10 cryptocurrencies by market capitalization.

Investors are attracted to Shiba Inu because it has a very low supply of only 21 billion tokens. This compares to other popular cryptocurrencies like Bitcoin, which has a supply of 21 million. This limited supply means that Shiba Inu could potentially increase in value over time as demand increases.

Shiba Inu also has a very active community on social media. The coin has its own Twitter account with over 400,000 followers and an active Telegram group with over 8,000 members. This community helps to generate interest and awareness of the coin, which could lead to more people buying it.

Overall, Shiba Inu is a promising new cryptocurrency with a lot of potentials. Its low supply and active community could help it to increase in value over time.

Saitama Inu:

Saitama Inu is a new cryptocurrency that was created in June of 2020. The team behind Saitama Inu is anonymous, but they are based in Japan. The currency is named after the Japanese anime character Saitama, who is known for his strength and power.

Saitama Inu has a total supply of 10,000,000,000 tokens and a circulating supply of 1,000,000,000 tokens. The currency is currently trading at $0.000016 USD.

The Saitama Inu team has plans to use the currency to build a decentralized social media platform. The platform will be called Soar and it will allow users to earn rewards for creating and sharing content.

So far, the team behind Saitama Inu has been very active on social media and they seem to be very committed to their project. The currency has a lot of potentials and it will be interesting to see how it develops over time.

Tezos:

Tezos is a new cryptocurrency that offers several unique features that make it an attractive investment. For one, Tezos uses a proof-of-stake algorithm instead of proof-of-work. This means that Tezos is more energy-efficient than other cryptocurrencies.

Another key feature of Tezos is its on-chain governance system. This system allows holders of Tezos tokens to vote on changes to the protocol. This helps to keep the Tezos network decentralized and responsive to the needs of its users.

Finally, Tezos has a strong development team behind it. The team is led by Arthur Breitman, who has a background in mathematics and computer science. This gives Tezos a solid foundation on which to build and grow.

Overall, Tezos is a promising new cryptocurrency with several unique features that make it worth investing in.

Cronos:

Cronos is a new cryptocurrency that was launched in June of 2018. Cronos is designed to be a more stable and secure form of currency than Bitcoin. It uses a Proof-of-Stake system, which means that users earn rewards for holding Cronos coins in their wallets. This helps to keep the currency more stable than other cryptocurrencies that use a Proof-of-Work system.

Cronos is also a very fast cryptocurrency. Transactions take only seconds to confirm. This makes it ideal for people who want to use cryptocurrency for everyday purchases.

Investors are bullish on Cronos, and the currency has already seen significant growth since its launch. If you’re looking for a new cryptocurrency to invest in, Cronos is a good option.

Conclusion:

If you’re ready to invest in cryptocurrency, exchanges are the most secure and user-friendly way to purchase, sell, and trade digital assets.

Koinbazar is the best leading cryptocurrency exchange in the world because it offers a number of unique features compared to other exchanges.

Koinbazar offers a wide variety of cryptocurrencies to invest in, including Bitcoin, Ethereum, Litecoin, and more. They also offer a variety of different payment methods, so you can choose the one that best suits your needs.

For one, Koinbazar allows users to trade in Indian rupees. This is important because it means that users do not have to convert their currency into another currency (such as US dollars) before trading. This makes the trading process simpler and more convenient.

Another unique feature of Koinbazar is that it offers a mobile Android and iOS app. This is convenient for users who want to trade on the go. The app is also very user-friendly and easy to navigate.

In addition, Koinbazar has low trading fees. It also offers a referral program, which gives users a 10K Shiba Inu (SHIB) if they refer new users to the platform.

#crypto #cryptos #cryptocurrency #invest #investments #investment #investing #cryptotrading 

Zena  Sporer

Zena Sporer

1596395400

Can AI Investing Solutions Outperform the Stock Markets? Ours Did

Around the world stock markets have been recording historic losses, with Market Economists now warning that the hit to the global economy is likely to be worse than the financial crisis of 2008 or the Great Depression.

In March 2020 the Dow Jones saw its steepest drop ever, recording losses that were even worse than during the Great Depression. No one was prepared for this crash, not even veteran investors, with many seeing their investments being severely depleted.

The impact of the Coronavirus just reinforces how volatile the stock markets can be and the damage situations like the Covid-19 pandemic can cause to your investments.

During these uncertain times, many investors are now crying out for an alternative investment solution to diversify and mitigate risk, while still yielding consistent returns.

8topuzoffers unique AI-based, risk-managed, trading software that works by utilizing the vast FX trading market and works typically with specific currency pairs.

#ai-investing #fintech #investing #passive-income #passive-investing #good-company

Lambda Functions with Practical Examples in Python

Introduction

When I first came across lambda functions in python, I was very much intimidated and thought they were for advanced Pythonistas. Beginner python tutorials applaud the language for its readable syntax, but lambdas sure didn’t seem user-friendly.

However, once I understood the general syntax and examined some simple use cases, using them was less scary.

Syntax

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code.

lambda argument(s): expression

A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression.

In the example code below, x is the argument and x+x is the expression.

#Normal python function
def a_name(x):
    return x+x
#Lambda function
lambda x: x+x

Before we get into practical applications, let’s mention some technicalities on what the python community thinks is good and bad with lambda functions.

Pros

  • Good for simple logical operations that are easy to understand. This makes the code more readable too.
  • Good when you want a function that you will use just one time.

Cons

  • They can only perform one expression. It’s not possible to have multiple independent operations in one lambda function.
  • Bad for operations that would span more than one line in a normal def function (For example nested conditional operations). If you need a minute or two to understand the code, use a named function instead.
  • Bad because you can’t write a doc-string to explain all the inputs, operations, and outputs as you would in a normal def function.

At the end of this article, we’ll look at commonly used code examples where Lambda functions are discouraged even though they seem legitimate.

But first, let’s look at situations when to use lambda functions. Note that we use lambda functions a lot with python classes that take in a function as an argument, for example, map() and filter(). These are also called Higher-order functions.

1. Scalar values

This is when you execute a lambda function on a single value.

(lambda x: x*2)(12)
###Results
24

In the code above, the function was created and then immediately executed. This is an example of an immediately invoked function expression or IIFE.

2. Lists

Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria. The syntax is filter(function, iterable). The iterable can be any sequence such as a list, set, or series object (more below).

The example below filters a list for even numbers. Note that the filter function returns a ‘Filter object’ and you need to encapsulate it with a list to return the values.

list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]

Map(). This is another inbuilt python library with the syntax map(function, iterable).

This returns a modified list where every value in the original list has been changed based on a function. The example below cubes every number in the list.

list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]

3. Series object

A Series object is a column in a data frame, or put another way, a sequence of values with corresponding indices. Lambda functions can be used to manipulate values inside a Pandas dataframe.

Let’s create a dummy dataframe about members of a family.

import pandas as pd
df = pd.DataFrame({
    'Name': ['Luke','Gina','Sam','Emma'],
    'Status': ['Father', 'Mother', 'Son', 'Daughter'],
    'Birthyear': [1976, 1984, 2013, 2016],
})

Lambda with Apply() function by Pandas. This function applies an operation to every element of the column.

To get the current age of each member, we subtract their birth year from the current year. In the lambda function below, x refers to a value in the birthyear column, and the expression is 2021(current year) minus the value.

df['age'] = df['Birthyear'].apply(lambda x: 2021-x)

Lambda with Python’s Filter() function. This takes 2 arguments; one is a lambda function with a condition expression, two an iterable which for us is a series object. It returns a list of values that satisfy the condition.

list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]

Lambda with Map() function by Pandas. Map works very much like apply() in that it modifies values of a column based on the expression.

#Double the age of everyone
df['double_age'] = 
df['age'].map(lambda x: x*2)

We can also perform conditional operations that return different values based on certain criteria.

The code below returns ‘Male’ if the Status value is father or son, and returns ‘Female’ otherwise. Note that apply and map are interchangeable in this context.

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

4. Lambda on Dataframe object

I mostly use Lambda functions on specific columns (series object) rather than the entire data frame, unless I want to modify the entire data frame with one expression.

For example rounding all values to 1 decimal place, in which case all the columns have to be float or int datatypes because round() can’t work on strings.

df2.apply(lambda x:round(x,1))
##Returns an error if some 
##columns are not numeric

In the example below, we use apply on a dataframe and select the columns to modify in the Lambda function. Note that we must use axis=1 here so that the expression is applied column-wise.

#convert to lower-case
df[['Name','Status']] = 
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)

Discouraged use cases

  1. Assigning a name to a Lambda function. This is discouraged in the PEP8 python style guide because Lambda creates an anonymous function that’s not meant to be stored. Instead, use a normal def function if you want to store the function for reuse.
#Bad
triple = lambda x: x*3
#Good
def triple(x):
     return x*3

2. Passing functions inside Lambda functions. Using functions like abs which only take one number- argument is unnecessary with Lambda because you can directly pass the function into map() or apply().

#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)

Ideally, functions inside lambda functions should take two or more arguments. Examples are pow(number,power) and round(number,ndigit). You can experiment with various in-built python functions to see which ones need Lambda functions in this context. I’ve done so in this notebook.

3. Using Lambda functions when multiple lines of code are more readable. An example is when you are using if-else statements inside the lambda function. I used the example below earlier in this article.

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

The same results can be achieved with the code below. I prefer this way because you can have endless conditions and the code is simple enough to follow. More on vectorized conditions here.

Conclusion

Many programmers who don’t like Lambdas usually argue that you can replace them with the more understandable list comprehensions, built-in functions, and standard libraries. Generator expressions (similar to list comprehensions) are also handy alternatives to the map() and filter() functions.

Whether or not you decide to embrace Lambda functions in your code, you need to understand what they are and how they are used because you will inevitably come across them in other peoples’ code.  

Source: https://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8

#lambda #python 

Pythonで実用的な例を使用したLambda関数

序章

Pythonでラムダ関数に最初に出会ったとき、私は非常に恐れていて、それらが高度なPythonista用であると思いました。初心者のPythonチュートリアルは、その言語の読みやすい構文を称賛していますが、ラムダは確かにユーザーフレンドリーではないようです。

ただし、一般的な構文を理解し、いくつかの単純なユースケースを検討すると、それらを使用することはそれほど怖くありませんでした。

構文

簡単に言うと、ラムダ関数は通常のPython関数と同じですが、定義時に名前がなく、1行のコードに含まれている点が異なります。

lambda argument(s): expression

ラムダ関数は、指定された引数の式を評価します。関数に値(引数)を指定してから、演算(式)を指定します。キーワードlambdaが最初に来る必要があります。完全なコロン(:)は、引数と式を区切ります。

以下のサンプルコードでは、xが引数で、x+xが式です。

#Normal python function
def a_name(x):
    return x+x
#Lambda function
lambda x: x+x

実際のアプリケーションに入る前に、Pythonコミュニティがラムダ関数の良い点と悪い点についていくつかの技術について言及しましょう。

長所

  • わかりやすい単純な論理演算に適しています。これにより、コードも読みやすくなります。
  • 一度だけ使う機能が欲しいときに便利です。

短所

  • 実行できる式は1つだけです。1つのラムダ関数で複数の独立した操作を行うことはできません。
  • 通常の関数で複数行にまたがる操作def (ネストされた条件付き操作など)には適していません。コードを理解するのに1、2分必要な場合は、代わりに名前付き関数を使用してください。
  • 通常の関数の場合のように、すべての入力、操作、および出力を説明するdoc-stringを記述できないため、問題がありますdef

この記事の最後では、Lambda関数が正当であるように見えても推奨されない、一般的に使用されるコード例を見ていきます。

ただし、最初に、ラムダ関数を使用する場合の状況を見てみましょう。map()やfilter()などの関数を引数として受け取るPythonクラスでは、ラムダ関数を頻繁に使用することに注意してください。これらは高階関数とも呼ばれます。

1.スカラー値

これは、単一の値に対してラムダ関数を実行する場合です。

(lambda x: x*2)(12)
###Results
24

上記のコードでは、関数が作成され、すぐに実行されました。これは、即時に呼び出される関数式またはIIFEの例です。

2.リスト

フィルター()。これは、特定の基準に適合する値のみを返すPython組み込みライブラリです。構文はfilter(function, iterable)です。iterableは、リスト、セット、またはシリーズオブジェクト(以下で詳しく説明します)などの任意のシーケンスにすることができます。

以下の例では、数値のリストをフィルタリングしevenます。filter関数は「Filterobject」を返すため、値を返すにはリストでカプセル化する必要があることに注意してください。

list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]

地図()。これは、構文が含まれるもう1つの組み込みのPythonライブラリです。map(function, iterable).

これにより、元のリストのすべての値が関数に基づいて変更された変更済みリストが返されます。以下の例では、リスト内のすべての数値を3乗しています。

list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]

3.シリーズオブジェクト

Seriesオブジェクトは、データフレーム内の列、言い換えると、対応するインデックスを持つ値のシーケンスです。Lambda関数を使用して、Pandasデータフレーム内の値を操作できます

家族のメンバーに関するダミーのデータフレームを作成しましょう。

import pandas as pd
df = pd.DataFrame({
    'Name': ['Luke','Gina','Sam','Emma'],
    'Status': ['Father', 'Mother', 'Son', 'Daughter'],
    'Birthyear': [1976, 1984, 2013, 2016],
})

PandasによるApply()関数を使用したLambda 。この関数は、列のすべての要素に操作を適用します。

各メンバーの現在の年齢を取得するために、現在の年からその誕生年を差し引きます。以下のラムダ関数では、xはbirthyear列の値を指し、式は2021(current year) minus the valueです。

df['age'] = df['Birthyear'].apply(lambda x: 2021-x)

PythonのFilter()関数を使用したLambda 。これには2つの引数が必要です。1つは条件式を使用したラムダ関数で、2つは反復可能で、これはシリーズオブジェクトです。条件を満たす値のリストを返します。

list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]

PandasによるMap()関数を使用したLambda 。Mapは、式に基づいて列の値を変更するという点で、apply()と非常によく似ています。

#Double the age of everyone
df['double_age'] = 
df['age'].map(lambda x: x*2)

特定の基準に基づいて異なる値を返す条件付き操作を実行することもできます。

以下のコードは、Status値が父親または息子の場合は「男性」を返し、それ以外の場合は「女性」を返します。このコンテキストでは、applyとは交換可能であることに注意してください。map

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

4.データフレームオブジェクトのラムダ

1つの式でデータフレーム全体を変更する場合を除いて、データフレーム全体ではなく、特定の列(シリーズオブジェクト)でLambda関数を使用することがほとんどです。

たとえば、すべての値を小数点以下1桁に丸めます。この場合、round()は文字列では機能しないため、すべての列はfloatまたはintデータ型である必要があります。

df2.apply(lambda x:round(x,1))
##Returns an error if some 
##columns are not numeric

以下の例では、データフレームに適用を使用し、Lambda関数で変更する列を選択します。式が列単位で適用されるように、ここで使用する必要があることに注意してください。axis=1

#convert to lower-case
df[['Name','Status']] = 
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)

推奨されないユースケース

  1. Lambda関数に名前を割り当てます。Lambdaは保存されることを意図していない無名関数を作成するため、これはPEP8pythonスタイルガイドでは推奨されていません。代わりに、def関数を再利用のために保存する場合は、通常の関数を使用してください。
#Bad
triple = lambda x: x*3
#Good
def triple(x):
     return x*3

2.Lambda関数内で関数を渡します。abs関数をmap()またはapply()に直接渡すことができるため、Lambdaでは1つの数値引数のみを取るような関数を使用する必要はありません。

#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)

理想的には、ラムダ関数内の関数は2つ以上の引数を取る必要があります。例は次のとおりです。さまざまな組み込みのPython関数を試してpow(number,power)、このコンテキストでLambda関数が必要な関数を確認できます。私はこのノートブックでそうしました。round(number,ndigit).

3.複数行のコードが読みやすい場合にLambda関数を使用します。例として、ラムダ関数内でif-elseステートメントを使用している場合があります。この記事の前半で、以下の例を使用しました。

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

以下のコードでも同じ結果が得られます。私はこの方法を好みます。なぜなら、あなたは無限の条件を持つことができ、コードは従うのに十分単純だからです。ベクトル化された条件の詳細については、こちらをご覧ください。

結論

Lambdasが気に入らない多くのプログラマーは、通常、Lambdasをより理解しやすいリスト内包表記、組み込み関数、および標準ライブラリに置き換えることができると主張しています。ジェネレータ式(リスト内包表記と同様)も、map()およびfilter()関数の便利な代替手段です。

Lambda関数をコードに含めるかどうかに関係なく、他の人のコードで必然的にLambda関数に遭遇するため、それらが何であるか、およびそれらがどのように使用されるかを理解する必要があります。  

ソース:https ://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8

#lambda  #python 

Funciones Lambda con Ejemplos Prácticos en Python

Introducción

Cuando me encontré por primera vez con las funciones lambda en python, estaba muy intimidado y pensé que eran para Pythonistas avanzados. Los tutoriales de Python para principiantes aplauden el lenguaje por su sintaxis legible, pero las lambdas ciertamente no parecían fáciles de usar.

Sin embargo, una vez que entendí la sintaxis general y examiné algunos casos de uso simples, usarlos fue menos aterrador.

Sintaxis

En pocas palabras, una función lambda es como cualquier función de python normal, excepto que no tiene nombre al definirla y está contenida en una línea de código.

lambda argument(s): expression

Una función lambda evalúa una expresión para un argumento dado. Le das a la función un valor (argumento) y luego proporcionas la operación (expresión). La palabra clave lambdadebe ir primero. Dos puntos completos (:) separan el argumento y la expresión.

En el código de ejemplo siguiente, x es el argumento y x+x es la expresión.

#Normal python function
def a_name(x):
    return x+x
#Lambda function
lambda x: x+x

Antes de entrar en aplicaciones prácticas, mencionemos algunos aspectos técnicos sobre lo que la comunidad de python cree que es bueno y malo con las funciones lambda.

ventajas

  • Bueno para operaciones lógicas simples que son fáciles de entender. Esto también hace que el código sea más legible.
  • Bueno cuando quieres una función que usarás solo una vez.

Contras

  • Solo pueden realizar una expresión. No es posible tener múltiples operaciones independientes en una función lambda.
  • Incorrecto para operaciones que abarcarían más de una línea en una def función normal (por ejemplo, operaciones condicionales anidadas). Si necesita uno o dos minutos para entender el código, use una función con nombre en su lugar.
  • Malo porque no puede escribir una cadena de documentos para explicar todas las entradas, operaciones y salidas como lo haría en una deffunción normal.

Al final de este artículo, veremos ejemplos de código de uso común en los que se desaconsejan las funciones de Lambda aunque parezcan legítimas.

Pero primero, veamos situaciones en las que usar funciones lambda. Tenga en cuenta que usamos mucho las funciones lambda con las clases de Python que toman una función como argumento, por ejemplo, map() y filter(). Estas también se llaman funciones de orden superior .

1. Valores escalares

Esto es cuando ejecuta una función lambda en un solo valor.

(lambda x: x*2)(12)
###Results
24

En el código anterior, la función se creó y luego se ejecutó inmediatamente. Este es un ejemplo de una expresión de función invocada inmediatamente o IIFE .

2. Listas

Filtrar(). Esta es una biblioteca incorporada de Python que devuelve solo aquellos valores que se ajustan a ciertos criterios. La sintaxis es filter(function, iterable). El iterable puede ser cualquier secuencia, como una lista, un conjunto o un objeto de serie (más abajo).

El siguiente ejemplo filtra una lista por evennúmeros. Tenga en cuenta que la función de filtro devuelve un 'Objeto de filtro' y debe encapsularlo con una lista para devolver los valores.

list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]

Mapa(). Esta es otra biblioteca de python incorporada con la sintaxismap(function, iterable).

Esto devuelve una lista modificada en la que todos los valores de la lista original se han cambiado en función de una función. El siguiente ejemplo reduce al cubo todos los números de la lista.

list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]

3. Objeto de serie

Un objeto Serie es una columna en un marco de datos, o dicho de otra manera, una secuencia de valores con índices correspondientes. Las funciones Lambda se pueden usar para manipular valores dentro de un marco de datos de Pandas .

Vamos a crear un marco de datos ficticio sobre los miembros de una familia.

import pandas as pd
df = pd.DataFrame({
    'Name': ['Luke','Gina','Sam','Emma'],
    'Status': ['Father', 'Mother', 'Son', 'Daughter'],
    'Birthyear': [1976, 1984, 2013, 2016],
})

Lambda con función Apply() de Pandas. Esta función aplica una operación a cada elemento de la columna.

Para obtener la edad actual de cada miembro, restamos su año de nacimiento del año actual. En la siguiente función lambda, x se refiere a un valor en la columna del año de nacimiento y la expresión es 2021(current year) minus the value.

df['age'] = df['Birthyear'].apply(lambda x: 2021-x)

Lambda con la función Filter() de Python . Esto toma 2 argumentos; uno es una función lambda con una expresión de condición, dos un iterable que para nosotros es un objeto de serie. Devuelve una lista de valores que cumplen la condición.

list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]

Lambda con función Map() de Pandas. El mapa funciona de manera muy similar a apply() en el sentido de que modifica los valores de una columna en función de la expresión.

#Double the age of everyone
df['double_age'] = 
df['age'].map(lambda x: x*2)

También podemos realizar operaciones condicionales que devuelven diferentes valores en función de ciertos criterios.

El siguiente código devuelve 'Masculino' si el valor de Estado es padre o hijo, y devuelve 'Femenino' en caso contrario. Tenga en cuenta que applyy mapson intercambiables en este contexto.

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

4. Lambda en el objeto Dataframe

Principalmente uso funciones de Lambda en columnas específicas (objeto de serie) en lugar de todo el marco de datos, a menos que quiera modificar todo el marco de datos con una expresión.

Por ejemplo, redondear todos los valores a 1 lugar decimal, en cuyo caso todas las columnas deben ser tipos de datos flotantes o int porque round() no puede funcionar en cadenas.

df2.apply(lambda x:round(x,1))
##Returns an error if some 
##columns are not numeric

En el siguiente ejemplo, usamos aplicar en un marco de datos y seleccionamos las columnas para modificar en la función Lambda. Tenga en cuenta que debemos usar axis=1aquí para que la expresión se aplique en forma de columna.

#convert to lower-case
df[['Name','Status']] = 
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)

Casos de uso no recomendados

  1. Asignación de un nombre a una función de Lambda. Esto no se recomienda en la guía de estilo de python PEP8 porque Lambda crea una función anónima que no debe almacenarse. En su lugar, utilice una función normal defsi desea almacenar la función para su reutilización.
#Bad
triple = lambda x: x*3
#Good
def triple(x):
     return x*3

2. Pasar funciones dentro de funciones Lambda. El uso de funciones como abslas que solo toman un argumento numérico no es necesario con Lambda porque puede pasar la función directamente a map() o apply().

#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)

Idealmente, las funciones dentro de las funciones lambda deberían tomar dos o más argumentos. Los ejemplos son pow(number,power)y round(number,ndigit).puede experimentar con varias funciones de python integradas para ver cuáles necesitan funciones de Lambda en este contexto. Lo he hecho en este cuaderno .

3. Usar funciones de Lambda cuando varias líneas de código son más legibles . Un ejemplo es cuando usa declaraciones if-else dentro de la función lambda. Utilicé el siguiente ejemplo anteriormente en este artículo.

#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')

Los mismos resultados se pueden lograr con el siguiente código. Prefiero esta forma porque puedes tener infinitas condiciones y el código es bastante simple de seguir. Más sobre condiciones vectorizadas aquí .

Conclusión

Muchos programadores a los que no les gustan las Lambdas generalmente argumentan que puede reemplazarlas con las listas de comprensión más comprensibles, las funciones integradas y las bibliotecas estándar. Las expresiones generadoras (similares a las listas de comprensión) también son alternativas prácticas a las funciones map() y filter().

Ya sea que decida o no adoptar las funciones de Lambda en su código, debe comprender qué son y cómo se usan porque inevitablemente las encontrará en el código de otras personas.  

Fuente: https://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8 

#python #lambda