我想将数据框中的一列拆分为多列。
这是我的数据框(df):
object_id shape geometry
1 450 polygon((6.6 51.2, 6.69 51.23, 6.69 51.2))
我想要的输出如下所示:
x y x y x y
6.6 51.2 6.69 51.23 6.69 51.2
我正在使用此代码:
df.geometry.str.split('( , )',expand=True)
但我收到错误。
最佳答案
有点 hacky,但我们可以进行一些字符串操作来重新创建您的数据框。
s = df['geometry'].str.replace('polygon\(\(||\)\)','')\
.str.split(',',expand=True).stack()\
.str.strip().str.split(' ').explode().to_frame('vals')
s['cords'] = s.groupby(level=[0,1]).cumcount().map({0 : 'x', 1 : 'y'})
df.join(s.set_index('cords',append=True).unstack([1,2]).droplevel(level=[0,1],axis=1))
object shape geometry x y x y x y
0 1 2 polygon((6.6 51.2, 6.69 51.23, 6.69 51.2)) 6.6 51.2 6.69 51.23 6.69 51.2
关于python - 如何使用不同的分隔符将Python中的列拆分为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73252550/