C initialize columns.add new datacolumn excl typeof bool
In pandas, you can add a new column to a DataFrame and specify the data type of the new column using the assign
method or the loc
method.
Here are a few examples:
Using the assign
method
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# add a new column with data type int
df = df.assign(C=7) # or df.assign(C=int)
print(df)
This will add a new column C
with values 7
and data type int
.
Using the loc
method
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# add a new column with data type int
df.loc[:, 'C'] = 7 # or df.loc[:, 'C'] = int
print(df)
This will also add a new column C
with values 7
and data type int
.
Excluding the bool
type
If you want to exclude the bool
type, you can use the dtype
parameter when creating the new column. For example:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# add a new column with data type int, excluding bool
df = df.assign(C=7, dtype=int)
print(df)
This will add a new column C
with values 7
and data type int
, excluding the bool
type.
Note that if you try to assign a bool
value to the new column, it will be converted to int
(0 or 1) if the dtype
is int
.