How to add datatype object to a dictionary in Python

Viewed 384

I am trying to dynamically add datatype objects to a dictionary, in order to specify the 'dtype' argument in the pd.read_csv function.

The problem is that simply passing 'key' : str or 'key' : float to dict.update() does not preserve the datatype objects and has no effect on the dtype argument.

I have attempted the following:

for column in list_of_columns:

    dict.update({column : str})

I expected to see something like:

{
'a' : str,
'b' : str,
'c' : str
}

But instead it produces:

{
'a' : <class 'str'>,
'b' : <class 'str'>,
'c' : <class 'str'>
}

Is there any way that I can explicitly place that datatype object in the dictionary?

2 Answers

You can use 'O' to specify the column is str (or Object in pandas term):

import pandas as pd
from io import StringIO

txt = """col1 col2
1 11
2 22
3 33
"""

df = pd.read_csv(StringIO(txt), sep = "\s+", dtype={'col1': 'O', 'col2': int})

Output:

print(df)
  col1  col2
0    1    11
1    2    22
2    3    33

df.dtypes
col1    object
col2     int64
dtype: object

df['col1'].apply(lambda x:isinstance(x, str))
0    True
1    True
2    True
Name: col1, dtype: bool

__name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

list_of_columns = ["a","b","c","d",1,1.1]
my_dict = {}
for column in list_of_columns:
    my_dict[column] = type(column).__name__  #or column.__class__.__name__
print(my_dict)

O/P:

{'a': 'str', 'b': 'str', 'c': 'str', 'd': 'str', 1: 'int', 1.1: 'float'}
Related