首页 > 解决方案 > 如何在 Python 中将数据类型对象添加到字典中

问题描述

我正在尝试将数据类型对象动态添加到字典中,以便在 pd.read_csv 函数中指定“dtype”参数。

问题是简单地将'key' : str'key' : float传递给 dict.update() 不会保留数据类型对象并且对 dtype 参数没有影响。

我尝试了以下方法:

for column in list_of_columns:

    dict.update({column : str})

我希望看到类似的东西:

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

但相反,它会产生:

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

有什么方法可以显式地将该数据类型对象放入字典中?

标签: pythonpandasdictionary

解决方案


您可以使用'O'来指定列是(str或术语):Objectpandas

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})

输出:

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

推荐阅读