【问题标题】:Is it necessary or beneficial to convert pandas column from object to string or int/float type?将 pandas 列从对象转换为字符串或 int/float 类型是否有必要或有益?
【发布时间】:2018-11-06 16:46:37
【问题描述】:

我有一个带有两个变量的熊猫 df

id    name
011    Peter Parker
022    Warners Brother
101    Bruce Wayne

目前两者都是对象类型。

假设我想通过一些条件过滤来创建更小的数据帧

df_small = df.loc[df['id']=='011']
df_small2 = df.loc[df['name']=='Peter Parker']

我已经想到并看到people 将对象类型列转换为其他特定数据类型。我的问题是,如果我已经可以根据字符串比较(如上所述)过滤它们,我是否需要这样做?将它们转换为特定的字符串或 int/float 类型有什么好处?

【问题讨论】:

  • 对于您的情况不需要转换,
  • 转换为数字类型的成本之一是'011' 将转换为11。对于'0011''011' 不同的情况,可能会出现问题
  • 这取决于你想用 df 做什么。例如,如果您要进行许多不同的 int 比较,最好只一次转换为 int,而不是 pandas 必须在每个函数调用上进行内部转换。
  • 没有“字符串类型”的熊猫列。这只是一个object 列。
  • 这些方法只对字符串可用。 x.str.contains(pat) 基本上只是 pat in x (按行)。例如,'e' in 'hello' 将起作用,而 'e' in 4 将抛出 TypeError,因为 in 不是数字类型的有效方法。

标签: python pandas dataframe types


【解决方案1】:

您询问了从 stringobject dtypes 转换的好处。至少有2个我能马上想到的。以以下数据框为例:

df = pd.DataFrame({'int_col':np.random.randint(0,10,10000), 'str_col':np.random.choice(list('1234567980'), 10000)})

>>> df.head()
   int_col str_col
0        7       0
1        0       1
2        1       8
3        6       1
4        6       0

此数据框包含 10000 行,并有一个 int 列和一个 object(即字符串)列用于显示。

内存优势:

整数列比对象列占用的内存少很多:

>>> import sys
>>> sys.getsizeof(df['int_col'])
80104
>>> sys.getsizeof(df['str_col'])
660104

速度优势:

由于您的示例是关于过滤的,因此请看一下过滤整数而不是字符串时的速度差异:

import timeit

def filter_int(df=df):
    return df.loc[df.int_col == 1]


def filter_str(df=df):
    return df.loc[df.str_col == '1']

>>> timeit.timeit(filter_int, number=100) / 100
0.0006298311000864488
>>> timeit.timeit(filter_str, number=100) / 100
0.0016585511100129225

在某些情况下,这种类型的速度差异可能会显着加快您的代码速度。

【讨论】:

  • 我要提一下,您可以通过分类数据以较低的成本获得两全其美的效果,例如区分 '011''11' 启用矢量化操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多