我无法将对象类型列转换为字符串

2024-09-30 12:11:54 发布

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

Df['column']
xxx345xxxhgf447jfhf576
Djfnfjf5678
0000004444000000
Xxx88xxx888xxx8888xxx88

八,

我试过了

Df['column'].astype(str)

Df['column'].astype('str')
Df['column'].astype('|S')

它仍然保持为对象数据类型


Tags: 对象dfcolumn数据类型strastypexxx345xxxhgf447jfhf576djfnfjf5678
2条回答

转换为str后,需要将其分配给列

Df['column'] = Df['column'].astype('string')
In [49]: df = pd.DataFrame({"column":["xxx345xxxhgf447jfhf576", "Djfnfjf5678", "0000004444000000","Xxx88xxx888xxx8888xxx88"]})

In [50]: df
Out[50]:
                    column
0   xxx345xxxhgf447jfhf576
1              Djfnfjf5678
2         0000004444000000
3  Xxx88xxx888xxx8888xxx88

In [51]: df.dtypes
Out[51]:
column    object
dtype: object

In [52]: df["column"] = df["column"].astype("string")

In [53]: df.dtypes
Out[53]:
column    string
dtype: object

熊猫的主要目标是加快速度和缓解压力 数值计算

这就是为什么在pandasonic类型中有各种版本的intfloat日期时间。 所有“其他”类型(例如字符串列表)最初被视为对象

直到版本1.0中,才引入了可保存的类型 一列值,如字符串bool,没有其他内容(以防止 在该列中添加一行(例如,int

创建数据帧时,可以传递dtype参数,但不幸的是 只允许一个值,因此不能指定不同的值 数据类型,分别对应于每列

要尝试将每个列类型转换为这些“新”数据类型,可以调用:

df2 = df.convert_dtypes()

现在,当您运行df2.info()时,您将得到:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
 -                  - 
 0   column  4 non-null      string
dtypes: string(1)
memory usage: 160.0 bytes

请注意,的类型现在是字符串(而不是对象df的情况相同)

相关问题 更多 >

    热门问题