我在Python2.7中使用了Pandas‘ver0.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 61)如何将id的所有元素转换为字符串?
2) --我最终将使用id为数据进行索引。与整数索引相比,在dataframe中使用字符串索引会减慢速度吗?
发布于 2020-03-05 20:34:55
反映最新实践的新答案:到目前为止(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)发布于 2017-10-03 10:15:20
你必须分配它,就像这样:-
df['id']= df['id'].astype(str)发布于 2019-06-28 19:43:32
就我个人而言,上述任何一项都不适合我。做了什么:
new_str = [str(x) for x in old_obj][0]https://stackoverflow.com/questions/22231592
复制相似问题