有没有办法在行而不是列中处理pandas.DataFrame的数据类型? [英] Is there a way to handle dtypes of pandas.DataFrame in rows and not columns?

查看:31
本文介绍了有没有办法在行而不是列中处理pandas.DataFrame的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

parquetfeatherhdf5等大数据文件格式能够与面向列的表配合使用,以加快读取列的速度。

在我的用例中,我希望从netcdf4文件切换到feather文件格式,因为我读取某些列的速度比使用netcdf4快10倍。但不幸的是,我正在丢失增加文件大小的dtype规范。

所以我的想法是定义行的数据类型,但 pandas 只接受列数据类型。

有没有一种方法可以更像以列为导向的表并为每一行指定dtype来处理DataFrame?

推荐答案

Pandas数据帧是一系列对象的集合,因此每列不能指定一个以上的数据类型(即带有[2, 'dog', 3]的列将具有dtypeobject,因为字符串[2, 2.5, 3]不能是int因为2.5

如果您想要基于行工作,则需要使用df.transpose()(或速记df.T)将您的DataFrame转置为行。如果您正在导入数据,则可以将数据帧转置并强制转换到每一列,如果您正在准备要导出的数据,则在导出转置之前的最后一步。

例如:

import pandas as pd

df = pd.DataFrame({'col_1': [1, 'cat', 3], 
                  'col_2': [4, 'dog', 6]},
                  index=['row_1', 'row_2', 'row_3'])

>>> df
      col_1 col_2
row_1     1     4
row_2   cat   dog
row_3     3     6

# Due to the the strings both columns are dtype object
>>> df.dtypes
col_1    object
col_2    object

# Transpose the df
>>> df.T
      row_1 row_2 row_3
col_1     1   cat     3
col_2     4   dog     6

# Now our data is in columns but still dtype object
>>> df.T.dtypes
row_1    object
row_2    object
row_3    object

# We can cast our columns (originally rows) to new dtypes now
>>> df.T.astype({'row_1': 'int', 'row_2': str, 'row_3': 'int'})
       row_1 row_2  row_3
col_1      1   cat      3
col_2      4   dog      6

>>> df.T.astype({'row_1': 'int', 'row_2': str, 'row_3': 'int'}).dtypes
row_1     int64
row_2    object
row_3     int64

这篇关于有没有办法在行而不是列中处理pandas.DataFrame的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆