在熊猫数据框的每一行上应用功能

时间:2019-03-13 15:36:16

标签: python pandas function dataframe apply

如何在以下数据框中的point_rotationCoordinates1列上应用函数Coordinates2

def point_rotation(point):
    """
    Changing axis
    """
    xcor, ycor = (700, 0)
    xcor1, ycor1 = (0, 0)
    xpoint, ypoint = point

    xnew = xpoint - xcor
    ynew = ypoint - ycor    
    xnew = xcor1 + math.cos(math.radians(270)) * (xnew - xcor1) - math.sin(math.radians(90)) * (ynew - ycor1)
    ynew = ycor1 + math.sin(math.radians(270)) * (xnew - xcor1) + math.cos(math.radians(90)) * (ynew - ycor1)
    return round(xnew, 0), round(ynew, 0)

这是我当前的数据框:

df = pd.DataFrame({'X_1': [-34.58, -15.78, -33.45, 4.60, 10.48],
                   'Y_1': [-58.66, -47.91, -70.66, -74.08, -66.86],
                   'X_2': [-3.58, -1.8, -3.5, 4.0, 1.48],
                   'Y_2': [-5.66, -4.1, -7.6, -7.8, -6.86]})

df['Coordinates1'] = list(zip(df.X_1, df.Y_1))
df['Coordinates2'] = list(zip(df.X_2, df.Y_2))

想要的输出:应该具有Coordinates3Coordinates4列,这些列基本上是通过传递point_rotationCoordinates1列而从Coordinates2函数派生的。

我尝试使用apply函数,但抛出一个错误:too many values to unpack (expected 2)

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果您使用列表理解。您的新点将是一个元组(类似于您定义Coordinates1Coordinates2的方式)

df['Coordinates3'] = [point_rotation(point) for point in df['Coordinates1']]

apply似乎也可以工作:)

df['Coordinates4'] = df['Coordinates2'].apply(point_rotation)

答案 1 :(得分:0)

就做

df['Coordinates3'] = df['Coordinates1'].apply(point_rotation)
df['Coordinates4'] = df['Coordinates2'].apply(point_rotation)
相关问题