Answers for "new column dataframe with boolean"

1

pandas convert column to boolean

df['column_name'] = df['column_name'].astype('bool')
For example:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random_integers(0,1,size=5), 
                  columns=['foo'])
print(df)
#    foo
# 0    0
# 1    1
# 2    0
# 3    1
# 4    1

df['foo'] = df['foo'].astype('bool')
print(df)
yields

     foo
0  False
1   True
2  False
3   True
4   True
Given a list of column_names, you could convert multiple columns to bool dtype using:

df[column_names] = df[column_names].astype(bool)
If you don't have a list of column names, but wish to convert, say, all numeric columns, then you could use

column_names = df.select_dtypes(include=[np.number]).columns
df[column_names] = df[column_names].astype(bool)
Posted by: Guest on March-12-2021
1

python conditionally create new column in pandas dataframe

# 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
Posted by: Guest on November-12-2020

Code answers related to "new column dataframe with boolean"

Python Answers by Framework

Browse Popular Code Answers by Language