熊猫:将系列的数据类型更改为字符串

发布于 2021-01-29 19:35:09

我将Pandas’ver 0.12.0’与Python 2.7结合使用,并具有如下数据框:

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系列由一些整数和字符串组成。它dtype在默认情况下是object。我想将的所有内容转换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为String?

2) 我最终将id用于为数据帧建立索引。与具有整数索引相比,在数据帧中具有String索引会降低速度吗?

关注者
0
被浏览
77
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以将id的所有元素转换为str使用apply

    df.id.apply(str)
    
    0        123
    1        512
    2      zhub1
    3    12354.3
    4        129
    5        753
    6        295
    7        610
    

    由OP编辑:

    我认为这个问题与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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看