在Python中创建一个可用的'str'对象

问题描述 投票:0回答:1

我需要创建一个单独的str对象,用于更大的代码块。

我有一个数据集作为名为“testset”的DataFrame读入。

testset = pd.read_csv('my_dataset_path')

然后我想将两个列Latitude和Longitude从“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个条目。有没有办法简化这个以获得所需的结果?我尝试过其他变形来形成“你”,但它永远不会完全正确。

python string pandas object
1个回答
1
投票

由于您使用pandas,最简单的方法是使用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
© www.soinside.com 2019 - 2024. All rights reserved.