Home > OS >  How to do arithmetic operation on tuples in column with other column
How to do arithmetic operation on tuples in column with other column

Time:07-30

I have a dataset where one column consists of tuples with the offset of X and Y coordinates of the from the center of a cirlce, which represents the perimeter. Then there are two more columns, one with the X coordinate of the center of the cirlce, and one with the Y coordinate of the center of the circle.

The dataframe looks like this:

X coordinate Y coordinate Offset
400 450 ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4))
500 550 ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3))
450 250 ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4))
525 800 ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3))
475 360 ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4))
510 550 ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3))

The first values in the tuples represent the offset on the X coordinate and the second on the Y coordinate. Like this (( X offset, Y offset), (X offset, Y offset))

My goal is to get a column where the tuples have the exact coordinates. So ((X coordinate X offset, Y coordinate Y offset), (X coordinate X offset, Y coordinate Y offset))

How can I make this column?

Thanks in advance!

CodePudding user response:

Use:

df['new_col'] = \
[tuple(map(tuple, arr)) 
 for arr in np.add(df[['X coordinate', 'Y coordinate']].to_numpy(),
                   np.array(df['Offset'].tolist()))]

Or:

def add_coordinates(serie):
    return tuple(map(lambda coords: tuple(np.add(serie[['X coordinate', 'Y coordinate']],
                                                 coords)),
                     serie['Offset']))
df['new_col'] = df.apply(add_coordinates, axis=1)

print(df)

   X coordinate  Y coordinate  \
0           400           450   
1           500           550   
2           450           250   
3           525           800   
4           475           360   
5           510           550   

                                              Offset  \
0  ((4, 1), (2, 1), (1, 1), (1, 2), (1, 3), (-4, 4))   
1  ((7, 1), (4, 2), (3, 0), (-2, 1), (-4, 1), (0,...   
2  ((4, 1), (2, 1), (1, 1), (1, 2), (1, 3), (-4, 4))   
3  ((7, 1), (4, 2), (3, 0), (-2, 1), (-4, 1), (0,...   
4  ((4, 1), (2, 1), (1, 1), (1, 2), (1, 3), (-4, 4))   
5  ((7, 1), (4, 2), (3, 0), (-2, 1), (-4, 1), (0,...   

                                             new_col  
0  ((404, 451), (402, 451), (401, 451), (401, 452...  
1  ((507, 551), (504, 552), (503, 550), (498, 551...  
2  ((454, 251), (452, 251), (451, 251), (451, 252...  
3  ((532, 801), (529, 802), (528, 800), (523, 801...  
4  ((479, 361), (477, 361), (476, 361), (476, 362...  
  • Related