如何在panda datafram中添加坐标数组作为行

2024-09-24 06:28:13 发布

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

我有一个文本文件,看起来像这样

,A,B
0,"[[-81.03443909  29.22855949]
 [-81.09729767  29.27094078]
 [-80.9937973   29.19698906]
 [-81.03072357  29.27445984]
 [-81.00499725  29.22187805]]","[[-81.42427063  28.30874634]
 [-81.42427063  28.30874634]
 [-81.42427063  28.30874634]
 [-81.36068726  28.29172897]
 [-81.42297363  28.30497551]
 [-81.48571777  28.24975777]
 [-81.35914612  28.29036331]]"

这就是我使用的^{cd1>}在放入熊猫数据帧之后的样子

^{pr2}$

我想它看起来像这样

^{pr3}$

在创建.txt文件之前,数据位于^{cd2>}中,我使用熊猫创建文本文件。所以,也许有一种方法可以跳过txt文件,并使用熊猫将数组拆分或格式化为一个整洁的数据帧。我在这干了一段时间了,我搞不懂怎么做。

这就是我如何生成数据的。我只复制2列来保持清晰,但将来我想传递一个唯一的点标识符

^{pr4}$

这是^{cd3>}的输出

[array([[-81.03443909,  29.22855949],
       [-81.09729767,  29.27094078],
       [-81.42297363,  28.30497551],
       [-81.48571777,  28.24975777],
       [-81.35914612,  28.29036331]], dtype=float32), array([[-81.49134064,  27.58896065],
       [-81.5194931 ,  27.63422012],
       [-81.5096283 ,  27.55581093],
       [-82.05444336,  26.93555069]], dtype=float32), array([[-82.18956757,  26.52433586],
       [-82.18956757,  26.52433586],
       [-82.18956757,  26.52433586],
       [-82.19439697,  26.53297997]], dtype=float32)]

这就是我如何创建数据帧并编写^{cd4>}文件

clusters = pd.DataFrame({'A':[clusters]})
clusters.to_csv('output.txt')

Tags: 文件数据方法txt数组arrayclusters文本文件
1条回答
网友
1楼 · 发布于 2024-09-24 06:28:13

这是一个起点:

In [72]: (pd.concat([pd.DataFrame(c, columns=['lat','lon']).assign(cluster=i)
   ....:             for i,c in enumerate(clusters)])
   ....:    .reset_index()
   ....:    .rename(columns={'index':'point'})
   ....: )
Out[72]:
    point        lat        lon  cluster
0       0 -81.034439  29.228559        0
1       1 -81.097298  29.270941        0
2       2 -81.422974  28.304976        0
3       3 -81.485718  28.249758        0
4       4 -81.359146  28.290363        0
5       0 -81.491341  27.588961        1
6       1 -81.519493  27.634220        1
7       2 -81.509628  27.555811        1
8       3 -82.054443  26.935551        1
9       0 -82.189568  26.524336        2
10      1 -82.189568  26.524336        2
11      2 -82.189568  26.524336        2
12      3 -82.194397  26.532980        2

或者使用多重索引:

^{pr2}$

相关问题 更多 >