简体   繁体   English

Pivot 特定行成列

[英]Pivot specific rows into columns

I have a pandas dataframe with the following structure我有一个 pandas dataframe 结构如下

Layer   distance    angle        X_UTM_0        Y_UTM_0
layer0  0           65.57315016  627792.796  4785636.433
layer0  66.77813701 44.90815387  627852.132  4785666.409
layer1  0           236.3706271  627854.177  4785669.487
layer1  71.46111277 244.9836507  627791.986  4785636.986
layer2  0           60.78662778  627791.393  4785637.658
layer2  70.2562004  57.98453037  627853.635  4785669.768

What I want to do is pivot the repeated layer0...n to columns to obtain something like我想要做的是 pivot 重复layer0...n到列以获得类似的东西

Layer   distance    angle       X_UTM_0     Y_UTM_0     X_UTM_1     Y_UTM_1
layer0  0       65.57315016 627792.796  4785636.433 627852.132  4785666.409     
layer1  0       236.3706271 627854.177  4785669.487 627791.986  4785636.986 
layer2  0       60.78662778 627791.393  4785637.658 627853.635  4785669.768

where i have both coordinates of each layer in the same row.我在同一行中拥有每一层的两个坐标。 I was thinking in using pivot_table, but I'm not sure how to approach this.我正在考虑使用pivot_table,但我不确定如何解决这个问题。 Any hint would be very appreciated.任何提示将不胜感激。

EDIT: To clarify, I do not need distance and angle columns, I can drop them.编辑:澄清一下,我不需要距离和角度列,我可以删除它们。 The idea is to convert to columns each field of repeated Layer row.这个想法是将重复Layer行的每个字段转换为列。

Assuming that the splitting condition is always in the 'distance' column, the following actions can be taken.假设分裂条件总是在'距离'列,可以采取以下动作。 If not, this response is invalid.如果不是,则此响应无效。

df1 = df[df['distance'] == 0.0]
df2 = df[~(df['distance'] == 0.0)]
df3 = df1.merge(df2[['Layer','X_UTM_0','Y_UTM_0']], on='Layer', how='outer')
df3.columns = ['Layer', 'distance', 'angle', 'X_UTM_0', 'Y_UTM_0', 'X_UTM_1', 'Y_UTM_1']

df3
    Layer   distance    angle   X_UTM_0 Y_UTM_0 X_UTM_1 Y_UTM_1
0   layer0  0.0 65.573150   627792.796  4785636.433 627852.132  4785666.409
1   layer1  0.0 236.370627  627854.177  4785669.487 627791.986  4785636.986
2   layer2  0.0 60.786628   627791.393  4785637.658 627853.635  4785669.768

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM