python - 如何在 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'>
}
有什么方法可以显式地将该数据类型对象放入字典中?
解决方案
您可以使用'O'
来指定列是(str
或术语):Object
pandas
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
推荐阅读
- javascript - Promise.race() 的实现
- javascript - 为什么在“getElementById”中使用驼峰式大小写而不在“onclick”中使用?
- java - 即使该列存在,我也会收到未找到列的异常
- wpf-controls - WPF复选框作为后面代码中的按钮
- android - 在android studio中将gradle设置为离线模式
- python - 如何在 Python 中将本地数据(图像)输入我的 Keras 网络?
- java - 使用 java/postgres 的计划报告
- oracle - 在过程中运行查询时出现问题
- c - C如何将struct分配给struct?
- java - 使用 Spring Boot 应用程序启用 HTTP 严格传输安全 (HSTS)