将列从object转换为string或int/float类型是必要的还是有益的?

2024-05-19 23:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫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类型有什么好处?你知道吗


Tags: 数据对象字符串nameid类型df条件
1条回答
网友
1楼 · 发布于 2024-05-19 23:25:14

您询问了从stringobject数据类型转换的好处。我能马上想到的至少有两个。以下面的数据帧为例:

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

在某些情况下,这种速度差异可能会显著加快代码的速度。你知道吗

相关问题 更多 >