我有一个pandas.DataFrame
{col
,其中有一个值"hello"
。我希望本专栏的数据类型为category
,单一类别为"hello"
。我可以做到以下几点
df["col"] = "hello"
df["col"] = df["col"].astype("catgegory")
df["col"]
三次才能达到这个目的吗李>df
在新列转换为category之前可能会占用大量空间。(数据帧相当大,有数百万行,值"hello"
实际上是一个更长的字符串。)在避免上述问题的同时,是否还有其他直接的、简短的、快速的方法来实现这一点
另一种解决办法是
df["col"] = pd.Categorical(itertools.repeat("hello", len(df)))
但是它需要itertools
和len(df)
的使用,我不确定内存使用情况如何
这个解决方案肯定能解决第一点,但不一定能解决第二点:
本质上
pd.Categorical
,使其成为一个分类列李>一种简单的方法是使用
df.assign
创建新变量,然后使用df.astype
以及特定列的数据类型字典将数据类型更改为category
这样,您就不必创建一系列长度等于数据帧的数据。您可以直接广播输入字符串,这样会节省一些时间和内存
正如您所看到的,这种方法是非常可伸缩的。您可以根据需要分配多个变量,有些变量还基于复杂函数。然后根据需要为它们设置数据类型
我们可以显式构建正确大小和类型的序列,而不是通过
__setitem__
隐式构建,然后转换:示例程序:
相关问题 更多 >
编程相关推荐