如何以线性间隔的增量扩展Python Pandas Dataframe

时间:2018-03-23 09:29:02

标签: python-3.x pandas

初学者问题:

我有一个像这样的pandas数据框:

x1   y1    x2    y2
0    0     2     2
10   10    12    12

我希望沿着x和y坐标将该数据帧扩展半个单位,如下所示:

x1   y1    x2    y2      Interpolated_X      Interpolated_Y
0    0     2     2            0                    0
0    0     2     2            0.5                  0.5
0    0     2     2            1                    1
0    0     2     2            1.5                  1.5
0    0     2     2            2                    2
10   10    12    12           10                   10
10   10    12    12           10.5                 10.5
10   10    12    12           11                   11
10   10    12    12           11.5                 11.5
10   10    12    12           12                   12

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我知道如何扩展这样的行的最简洁方法是groupby.apply。在pandas中使用像itertuples这样的东西可能会更快,但是代码会更复杂一些(如果你的数据集更大,请记住这一点。)

groupby将每行发送到apply函数的索引(如果不是只运行reset_index,则每个行的索引必须是唯一的)。我可以从apply返回一个DataFrame,因此我们可以从一行扩展到多行。

警告,您的x2-x1y2-y1距离必须相同或不起作用。

import pandas as pd
import numpy as np

def expand(row):
    row = row.iloc[0] # passes a dateframe so this gets reference to first and only row
    xdistance = (row.x2 - row.x1)
    ydistance = (row.y2 - row.y1) 
    xsteps = np.arange(row.x1, row.x2 + .5, .5) # create steps arrays
    ysteps = np.arange(row.y1, row.y2 + .5, .5)
    return (pd.DataFrame([row] * len(xsteps)) # you can expand lists in python by multiplying like this [val] * 3 = [val, val, val]
              .assign(int_x = xsteps, int_y = ysteps))

(df.groupby(df.index) # "group" on each row
   .apply(expand) # send row to expand function
   .reset_index(level=1, drop=True)) # groupby gives us an extra index we don't want

开始df

x1   y1    x2    y2
0    0     2     2
10   10    12    12

结束df

    x1  y1  x2  y2  int_x   int_y
0   0   0   2   2   0.0     0.0
0   0   0   2   2   0.5     0.5
0   0   0   2   2   1.0     1.0
0   0   0   2   2   1.5     1.5
0   0   0   2   2   2.0     2.0
1   10  10  12  12  10.0    10.0
1   10  10  12  12  10.5    10.5
1   10  10  12  12  11.0    11.0
1   10  10  12  12  11.5    11.5
1   10  10  12  12  12.0    12.0