【发布时间】:2014-04-09 12:12:07
【问题描述】:
我在 Python 2.7 中使用 Pandas 'ver 0.12.0' 并有如下数据框:
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 的所有元素转换为字符串?
2) 我最终将使用id 为数据帧建立索引。与使用整数索引相比,在数据帧中使用字符串索引会减慢速度吗?
【问题讨论】:
-
不知道为什么你会得到那个输出,因为
astype对我来说很好,至少在 0.13.1 版本中,也许 0.12.0 有一个错误?在回答您的第二点时,是的,它可能会更慢,因为字符串比较不会比整数比较快,但我会先分析一下,这也取决于大小 -
您已经设置了列,对吧? df['id'] = df['id'].astype(str)
-
@Andy Hayden,是的,我预约了,但这是我认为出乎意料的输出。
-
以什么方式出乎意料?
-
它只返回每个系列元素的第一个字符,正如我在
df['id'].astype(str)下的问题中提出的那样