Pandas: 将Series的数据类型更改为字符串

171 投票
11 回答
667706 浏览
提问于 2025-04-17 21:09

我在使用 Pandas 的 'ver 0.12.0' 版本,配合 Python 2.7,并且有一个数据框(dataframe),内容如下:

df = pd.DataFrame({'id' : [123,512,'zhub1', 12354.3, 129, 753, 295, 610],
                    'colour': ['black', 'white','white','white',
                            'black', 'black', 'white', 'white'],
                    'shape': ['round', 'triangular', 'triangular','triangular','square',
                                        'triangular','round','triangular']
                    },  columns= ['id','colour', 'shape'])

这个 id 列里有一些整数和字符串。默认情况下,它的 dtypeobject。我想把 id 列里的所有内容都转换成字符串。我试过用 astype(str),结果如下。

df['id'].astype(str)
0    1
1    5
2    z
3    1
4    1
5    7
6    2
7    6

1) 我该怎么把 id 列里的所有元素都转换成字符串呢?

2) 我最终会用 id 来做数据框的索引。用字符串作为索引会比用整数索引慢吗?

11 个回答

7

你可以使用:

df.loc[:,'id'] = df.loc[:, 'id'].astype(str)

这就是他们推荐这个解决方案的原因:Pandas文档

总结一下:

为了回应一些答案:

df['id'] = df['id'].astype("string")

在给定的例子中,这个方法会出错,因为它会尝试转换为StringArray,而这个类型无法处理字符串中的任何数字。

df['id']= df['id'].astype(str)

对我来说,这个解决方案会抛出一些警告:

> SettingWithCopyWarning:  
> A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
8

说实话,上面提到的方法对我都没用。

new_str = [str(x) for x in old_obj][0]
70

你必须像这样给它赋值:

df['id']= df['id'].astype(str)
125

你可以通过使用 apply 把所有的 id 元素转换成 str 类型。

df.id.apply(str)

0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610

原作者补充:

我觉得问题和 Python 的版本有关(2.7),这个方法有效:

df['id'].astype(basestring)
0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610
Name: id, dtype: object
232

这是一个新的回答,反映了目前的最新做法:到现在为止(v1.2.4版本),无论是用astype('str')还是astype(str)都不能正常工作。

根据文档,一个Series(可以理解为一列数据)可以通过以下几种方式转换为字符串类型:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

撰写回答