Python Dictionary of datatypes to dataframe

Viewed 38

I am trying to convert datatypes in a dataframe in python from a dictionary, so far I cannot see references online. I can only see change columns in a dataframe from a dictionary. https://kanoki.org/2019/04/06/pandas-map-dictionary-values-with-dataframe-columns/

This is the dictionary that contains the datatype. On the left is the current datatype while on the right is the datatype to convert to.

type_conversion = {
    "bigint": "int64",
    "boolean": "bool",
    "character varying": "str",
    "double precision": "float64",
    "integer": "int32",
    "numeric": "float64",
    "timestamp without time zone": "datetime64"
}

Any way on how to achieve this?

1 Answers

I think you are looking for this:

df.dtypes.to_dict()

example:

df = pd.DataFrame({'par1': np.array([1]).astype('i'), "par2": np.array([2]).astype('f')})
df.types

output:
output

df.dtypes.to_dict()

output: output

Related