Pandas 将Series的数据类型更改为字符串 | 您所在的位置:网站首页 › str转换为字符串python › Pandas 将Series的数据类型更改为字符串 |
Pandas 将Series的数据类型更改为字符串
在本文中,我们将介绍如何使用Pandas将Series(一维数据集)的数据类型更改为字符串类型。 首先,让我们创建一个Series。我们将使用以下代码创建一个带有数字和字符串值的Series。 import pandas as pd s = pd.Series([1, 2, '3', 'four']) print(s)输出: 0 1 1 2 2 3 3 four dtype: object我们可以看到Series中有整数和字符串,其中包括了一个字符串数字。现在,让我们将此Series中的所有内容转换为字符串类型。 使用astype()函数将Series中的数据类型更改为字符串类型。这是一种将一个Pandas对象(Series、Dataframe等)中的一列数据类型转换为另一种类型的方法。在本例中,我们将数据类型从object转换为str。 s = s.astype(str) print(s)输出: 0 1 1 2 2 3 3 four dtype: object现在,我们可以看到所有的值都被转换成了字符串。 让我们看一个更实际的例子。假设我们有一份包含“年龄”和“收入”的数据集,并且“年龄”列中的值是整数。但是,我们需要将该列的数据类型更改为字符串类型。 data = {'age': [25, 35, 40, 28], 'income': [50000, 65000, 80000, 45000]} df = pd.DataFrame(data) print(df) print(df.dtypes)输出: age income 0 25 50000 1 35 65000 2 40 80000 3 28 45000 age int64 income int64 dtype: object这里,我们可以看到“年龄”列的数据类型为int64。为了将其转换为字符串类型,我们使用方法astype(). df['age'] = df['age'].astype(str) print(df) print(df.dtypes)输出: age income 0 25 50000 1 35 65000 2 40 80000 3 28 45000 age object income int64 dtype: object现在,“年龄”列的数据类型已经更改为字符串。 阅读更多:Pandas 教程 总结在本文中,我们介绍了如何使用astype()函数将一个Pandas对象中列的数据类型更改为另一种类型。在本例中,我们将Series中的所有值从object类型转换为str类型,将DataFrame中的年龄列从int64类型转换为str类型。astype()函数为数据类型转换提供了一种快捷简便的方法。 |
CopyRight 2018-2019 实验室设备网 版权所有 |