python - 如何使用 dtype 预定义数据帧的 dtypes

标签 python pandas dataframe

这个数据类型是如何工作的,我对这个东西很着迷。

1:首先使用python的默认类型:无法工作,引发错误

bins = pd.DataFrame(dtype=[str, int, int], columns=["chrom", "start", "end"])
raise error : TypeError: data type not understood

2:使用numpy的dtype函数。确实有效,但结果错误。

bins = pd.DataFrame(dtype=np.dtype("str","int32","int32"), columns=["chrom", "start", "end"])
bins.dtypes
output:
chrom    object
start    object
end      object
dtype: object

最佳答案

您可以首先使用列名称定义一个DataFrame,然后使用 .astype 更改类型就像下面这样:

bins = pd.DataFrame(columns=["chrom", "start", "end"])

bins = bins.astype({'chrom':'object',
                    'start':'int64',
                    'end':'int64'})

print(bins.dtypes)
chrom    object
start     int64
end       int64
dtype: object

注意:我使用 object 作为类型来定义 string 列,这就是 text 列的结构在pandas中定义

关于python - 如何使用 dtype 预定义数据帧的 dtypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192954/

相关文章:

python - 使用 urllib2 抓取 Biography.com

python - 如何在 Pandas 的数据框中组合两列?

python - 向 Pandas DataFrame 箱线图添加图例

在r中重新格式化数据

r - 根据外部标准计算一行中的条目数

Python 设置查找效率

Python 尝试/除了不工作

python - 根据其他 Dataframe 添加特定列值

python - 如何使用用户函数来填充pandas中的fillna()

python - 如何预处理 "big data"tsv 文件并将其加载到 python 数据帧中?