I'm currently working on a project where I need to transform the data in a pandas dataframe to another representation that uses a different (non-python) type system. The transformation is not covered by one of pandas' serialization/io methods. In particular I need to map the pandas dataframe column data types to those of the other type system. For starters, let's assume the target type system to be pretty simple having only string, integer, float, boolean, and timestamp types.
So, I started by looking at the dataframe dtypes with a simple example:
import pandas as pd
from datetime import datetime
headers = ["string", "integer", "float", "boolean", "timestamp"]
data = [["a", 1, 1.0, True, datetime.now()]]
df = pd.DataFrame(data, columns=headers)
dts = df.dtypes
for col in dts.index:
print("column: ", col, " - type: ", dts[col].name)
which gave me:
column: string - type: object
column: integer - type: int64
column: float - type: float64
column: boolean - type: bool
column: timestamp - type: datetime64[ns]
Okay, getting object for string columns is not nice so I found the Dataframe.convert_dtypes() method which, when added to the dataframe creation line gave me:
column: string - type: string
column: integer - type: Int64
column: float - type: Int64
column: boolean - type: boolean
column: timestamp - type: datetime64[ns]
Better for my string column, but now I'm getting Int64 (with a capital "I") for both my integer and float columns (!) and boolean instead of bool. (Okay, I'm back to float64 when I use a "real" float such as "0.1" in the example data but still...)
That made me wonder whether I'm on the right track with this approach. I then looked at the numpy dtype documentation and the numpy dtype charcodes. But there doesn't seem to be a charcode for every possible data type, esp. not for string types. Also, pandas' extension dtypes that I get after applying convert_dtypes() don't have the char attribute anymore.
So my question is, what is the canonical way to obtain data type identifiers for the columns in a pandas dataframe that I can use for mapping those data types to another type system?