astype 不适用于 Pandas 数据框

问题描述 投票:0回答:2

我有一个名为消息的数据框,其中数据看起来像

message             length  class
hello, Come here      16     A
hi, how are you       15     A 
what is it            10     B
maybe tomorrow        14     A

当我这样做时

messages.dtypes

它向我展示了

class      object
message    object
Length      int64
dtype: object

然后我尝试将消息列转换为字符串类型

messages['message'] = messages['message'].astype(str)
print messages.dtypes

它仍然向我展示

class      object
message    object
Length      int64
dtype: object

我做错了什么。为什么它不转换为字符串?

Windows 10 上的 Python 版本 2.7.9
熊猫版本0.15.2

python pandas dataframe
2个回答
5
投票

没有“字符串”数据类型。在 pandas 中,字符串存储为对象。

在 numpy 中,您可以拥有字符串数据类型,但它们是固定长度的,因此仍然没有“字符串数据类型”。有 5 个字符字符串的数据类型、10 个字符字符串的数据类型等,但“字符串”本身没有数据类型。 Pandas 使用

object
作为字符串的数据类型,以便您可以对字符串执行大小更改操作(例如,将它们与其他字符串连接),而无需使用新的字符串长度重新创建整个列。


0
投票

下面是我将对象数据类型转换为字符串数据类型的演示代码希望对您有帮助

import pandas as pd

# Create a sample DataFrame with an 'object' datatype column
data = {'A': ['foo', 'bar', 'baz']}
df = pd.DataFrame(data)

# Convert the 'A' column from object to string datatype
df['A'] = df['A'].astype(str)

# Verify the datatype conversion
print(df.dtypes)

如果您想了解更多有关 pandas 的信息,可以访问我的博客:- 我的博客

© www.soinside.com 2019 - 2024. All rights reserved.