在Python中创建可用的“str”对象

2024-09-27 00:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个str对象,以便在更大的代码块中使用。你知道吗

我将一个数据集作为数据帧读入,称为“testset”

testset = pd.read_csv('my_dataset_path')

然后我想将“testset”中的两列纬度和经度组合成一个str对象。你知道吗

我希望它看起来像这样:

u = u"""Latitude,Longitude
42.357778,-71.059444
39.952222,-75.163889
25.787778,-80.224167
30.267222, -97.763889"""

但当我尝试以下方法时:

Lat = testset['Latitude'].astype(str) #creates a series
Long = testset['Longitude'].astype(str) #creates a series
Lat_str=Lat.str.cat(sep=' ') #coerces a 'str' object
Long_str=Long.str.cat(sep=' ') #coerces a 'str' object
u= Lat_str,Long_str

我只是从两个str对象得到一个元组。你知道吗

我不想列出最后一个'str'对象“u”中的每一项,因为这些列有超过1000个条目。有没有一种方法可以简化这个过程以获得期望的结果?我试过其他的变体来形成“u”,但从来都不对。你知道吗


Tags: 数据对象方法seplongcatserieslat
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:15

既然您使用熊猫,最简单的方法就是使用to_csv()

u = testset[['Latitude' ,'Longitude']].to_csv(index=False)
print(u)

输出:

Latitude,Longitude
42.357778,-71.059444
39.952222,-75.163889
25.787778,-80.22416700000001
30.267221999999997,-97.763889

如果要避免使用30.267221999999997,,请舍入:

u = testset[['Latitude' ,'Longitude']].round(6).to_csv(index=False)
print(u)

输出:

Latitude,Longitude
42.357778,-71.059444
39.952222,-75.163889
25.787778,-80.224167
30.267222,-97.763889

相关问题 更多 >

    热门问题