Ejemplo 1: los pandas crean una nueva columna condicionada a otras columnas
# For creating new column with multiple conditions
conditions = [
(df['Base Column 1'] == 'A') & (df['Base Column 2'] == 'B'),
(df['Base Column 3'] == 'C')]
choices = ['Conditional Value 1', 'Conditional Value 2']
df['New Column'] = np.select(conditions, choices, default='Conditional Value 1')
Ejemplo 2: agregue un valor a un campo existente en el marco de datos de pandas después de verificar las condiciones
# Create a new column called based on the value of another column
# np.where assigns True if gapminder.lifeExp>=50
gapminder['lifeExp_ind'] = np.where(gapminder.lifeExp >= 50, True, False)
gapminder.head(n=3)
Ejemplo 3: Python crea condicionalmente una nueva columna en el marco de datos de pandas
# If you only have one condition use numpy.where()
# Example usage with np.where:
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
# Add new column based on single condition:
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
# If you have multiple conditions use numpy.select()
# Example usage with np.select:
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
# Set the conditions for determining values in new column:
conditions = [
(df['Set'] == 'Z') & (df['Type'] == 'A'),
(df['Set'] == 'Z') & (df['Type'] == 'B'),
(df['Type'] == 'B')]
# Set the new column values in order of the conditions they should
# correspond to:
choices = ['yellow', 'blue', 'purple']
# Add new column based on conditions and choices:
df['color'] = np.select(conditions, choices, default='black')
print(df)
# Returns:
Set Type color
0 Z A yellow
1 Z B blue
2 X B purple
3 Y C black
Ejemplo 4: agregue un valor a un campo existente en el marco de datos de pandas después de verificar las condiciones
gapminder['gdpPercap_ind'] = gapminder.gdpPercap.apply(lambda x: 1 if x >= 1000 else 0)
gapminder.head()
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)