Answers for "pandas if any column is true write column"

3

pandas if else new column

# Method 1:
df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
#or
df.loc[df['set_of_numbers'] <= 4, 'equal_or_lower_than_4?'] = 'True' 

# Method 2:
df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
#or
df['name_match'] = df['First_name'].apply(lambda x: 'Match' if x == 'Bill' else 'Mismatch')

# or
df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match'  
df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch'
Posted by: Guest on April-13-2021
0

validating columns in pandas on the basis of dtypes

import pandas as pd
import pandera as pa

df = pd.DataFrame({
    "column1": [1, 2, 3],
    "column2": ["a", "b", "c"],
})

column1_schema = pa.Column(pa.Int, name="column1")
column2_schema = pa.Column(pa.String, name="column2")

# pass the dataframe as an argument to the Column object callable
df = column1_schema(df)
validated_df = column2_schema(df)

# or explicitly use the validate method
df = column1_schema.validate(df)
validated_df = column2_schema.validate(df)

# use the DataFrame.pipe method to validate two columns
validated_df = df.pipe(column1_schema).pipe(column2_schema)
Posted by: Guest on February-17-2021

Code answers related to "pandas if any column is true write column"

Python Answers by Framework

Browse Popular Code Answers by Language