Maneiras de aplicar uma condição if no Pandas DataFrame
Geralmente, em um DataFrame do Pandas, a condição if pode ser aplicada em colunas, linhas ou em células individuais. O outro documento ilustra cada um deles com exemplos.
Em primeiro lugar, devemos criar o seguinte DataFrame:
# importing pandas as pd
import pandas as pd
# create the DataFrame
df = pd.DataFrame({
'Product': ['Umbrella', 'Matress', 'Badminton',
'Shuttle', 'Sofa', 'Football'],
'MRP': [1200, 1500, 1600, 352, 5000, 500],
'Discount': [0, 10, 0, 10, 20, 40]
})
# display the DataFrame
print(df)
# if condition with column conditions given
# the condition is if MRP of the product <= 2000
# and discount > 0 show me those items
df[(df['MRP'] <= 2000) & (df['Discount'] > 0)]
# if condition with row tuple given
df[(df['Product'] == 'Sofa') & (df['MRP'] == 5000) & (df['Discount']== 20)]
# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({
'Product': ['Umbrella', 'Matress', 'Badminton',
'Shuttle', 'Sofa', 'Football'],
'MRP': [1200, 1500, 1600, 352, 5000, 500],
'Discount': [0, 10, 0, 10, 20, 40]
})
# Print the dataframe
print(df)
# If condition on column values using Lambda function
df['Discount'] = df['Discount'].apply(lambda x : 20 if x > 20 else x)
print(df)
# If condition on a cell value using iloc() or loc() functions
# iloc() is based on index search and loc() based on label search
# using iloc()
if df.iloc[2, 1] > 1500:
print("Badminton Price > 1500")
else:
print("Badminton Price < 1500")
# using loc()
print(df.loc[2, 'MRP'])
if df.iloc[2, 'MRP'] > 1500:
print("Badminton Price > 1500")
else:
print("Badminton Price < 1500")
<button class="vote-this" data-type="like" style="margin-right:0;margin-left:0">
Gostar</button>
Artigos Recomendados
Página :
Artigo contribuído por:
Vote na dificuldade
<button class="btn" data-gfg-action="article-difficulty" data-rating="1">Fácil</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="2">Normal</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="3">Médio</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="4">Duro</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="5">Especialista</button>
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva