python - 行中列表的元素

标签 python csv pandas

我有几个多边形以及一些点与这些多边形的距离。我尝试用 pandas 编写 csv,其中每个点和多边形之间的距离将出现在单独的行中。我得到了这个:

poly total inside outside dist
1000   2     0      2     [16015,5678]
1100   1     0      1     [5267]

我想要这样:

poly total inside outside dist
1000   2    0       2     16015
1000   2    0       2     5678
1100   1    0       1     5267

在查看了之前的问题后,我尝试了以下操作[ How to write nth value of list into csv file

distance =[]
for row in arcpy.da.SearchCursor(outSide, ["SHAPE@XY"]):
            px, py = row[0]
            zipPoint=point(px,py)
            Distance.append(int(zipPoint.calDist(PolyCenter)))
for i in distance:
    df.loc[polygon,"distance"]=distance
    df.loc[zipCode,"Total"]=count
    df.loc[zipCode,"Inside"]=insideNum
    df.loc[zipCode,"Outside"]=outsideNum

但它在 csv 中给了我相同的结果。如有任何帮助,我们将不胜感激。

最佳答案

您可以使用str.len获取由numpy.repeat重复的列表的长度与 flattening lists然后join原始栏目:

from  itertools import chain

s = pd.Series(list(chain.from_iterable(df.dist)),
                   index=np.repeat(df.index.values, df.pop('dist').str.len())).rename('dist')
print (s)
0    16015
0     5678
1     5267
Name: dist, dtype: int64

print (df.join(s).reset_index(drop=True))
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267

另一个解决方案 MultiIndex :

names = ['poly','total', 'inside','outside']
df = df.set_index(names)
mux = pd.MultiIndex.from_tuples(np.repeat(df.index.values, df.dist.str.len()), names=names)
df2 = pd.DataFrame({'dist':list(chain.from_iterable(df.dist))}, index=mux).reset_index()
print (df2)
   poly  total  inside  outside   dist
0  1000      2       0        2  16015
1  1000      2       0        2   5678
2  1100      1       0        1   5267

关于python - 行中列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084260/

相关文章:

python - ValueError : view limit minimum -5. 1000000000000005 小于 1 并且是无效的 Matplotlib 日期值

python - pytest Monkeypatch 终端大小

python - 如何使用 pandas 读取带有逗号的数字的 *.csv 文件?

pandas - 有没有办法像 Pyspark 那样将 Pandas 数据保存在多个(parquet/csv)文件中?

python - 创建 |N| x |M|来自哈希表的矩阵

python - 比较 2 个数据帧并检查 id 列值是否在其他数据帧列中。如果该值存在则更改相应的列

python - 查找子序列(非连续的)

python - 使用反射从包中加载和实例化模块?

python - 单独线程中的 Pandas pd.concat() 显示没有加速

python - 在 groupby Pandas 对象上应用滚动()时重复多索引