pandas change datatype of column code example
Example 1: change dataframe column type
>>> df.astype({'col1': 'int32'}).dtypes
col1 int32
col2 int64
dtype: object
Example 2: convert a pandas column to int
my_series = pd.to_numeric(my_series)
df["a"] = pd.to_numeric(df["a"])
Example 3: set column datatype pandas
df = pd.read_csv("weather.tsv", sep="\t",
dtype={'Day': str,'Wind':int64})
df.dtypes
Example 4: astype float across columns pandas
In [273]: cols = df.columns.drop('id')
In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
In [275]: df
Out[275]:
id a b c d e f
0 id_3 NaN 6 3 5 8 1.0
1 id_9 3.0 7 5 7 3 NaN
2 id_7 4.0 2 3 5 4 2.0
3 id_0 7.0 3 5 7 9 4.0
4 id_0 2.0 4 6 4 0 2.0
In [276]: df.dtypes
Out[276]:
id object
a float64
b int64
c int64
d int64
e int64
f float64
dtype: object