将列类型编辑为固定宽度字符串(在现有 Pandas 数据框中)



我在熊猫数据帧中有一列字符串对象。我想将它们更改为效率低得离谱的固定宽度字符串类型。

有许多 SO 答案(如何在 pandas 数据帧中按列设置 dtypes)详细介绍了如何对数值类型执行此操作:

import pandas as pd
import numpy as np
df = pd.Series(["1", "22", "333", "4444", "55555"], name="c").to_frame()
df["c"] = df["c"].astype("int")
list(df.dtypes)  # [dtype('int64')]

。但这对于固定宽度的字符串失败:

df = pd.Series(["1", "22", "333", "4444", "55555"], name="c").to_frame()
df["c"] = df["c"].astype("|S2")
print list(df.dtypes)  # [dtype('O')]

df["c"]的内容最终应与以下内容相同:

print np.array(["1", "22", "333", "4444", "55555"]).astype("|S2")
['1' '22' '33' '44' '55']

那么..如何更改数据帧列的dtype?(没有分配一个全新的数据帧 - 只想更改那一列)

您可以在重新分配之前pop该列:

In [11]: df.dtypes
Out[11]:
c    object
dtype: object
In [12]: df['c'] = df.pop('c').astype('|S2')
In [13]: df.dtypes
Out[13]:
c    |S2
dtype: object

最新更新