How to concatenate pairs of row elements into a new column in a pandas dataframe?

2024/11/17 21:25:20

I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question)
I have a larger example sample here, but here's a sample:

start_column = 8    
df = pd.DataFrame(columns = ['x1','y1','x2','y2'],data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(7):df.insert(0,'c'+str(7-i),'x')
df

I want to create a new column in the DataFrame as a list of xy pairs, as in: df["coordinates"]=[[x1,y1],[x2,y2],[x3,y3]....]

What I've tried so far:

for row in df.iterrows():for i in range(1,total_count_of_xy_rows):df["coordinates"]= df[["x{}".format(i),"y{}".format(i)]].values.tolist()print(df)

Is there a better way to do this?

Answer

You can create the new column by .apply-ing a custom list comprehension function across the different rows:

start_column = 8    
coordinates_list = list(zip(df.columns[(start_column-1):-1:2],df.columns[start_column::2]))
df['coordinates'] = df.apply(lambda row: [(row[x], row[y]) for x,y in coordinates_list if not any((pd.isna(row[x]), pd.isna(row[y])))], axis=1)

Using this example input, with the coordinate columns starting from the 8th column, as you stated in a comment:

df = pd.DataFrame(columns = ['x1','y1','x2','y2'],data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(start_column-1):df.insert(0,'c'+str(start_column-1-i),'x')
dfc1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2
0   x   x   x   x   x   x   x   0   0   1.0 0.0
1   x   x   x   x   x   x   x   0   1   2.0 3.0
2   x   x   x   x   x   x   x   -1  -2  NaN NaN

This will produce this output:

c1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2  coordinates
0   x   x   x   x   x   x   x   0   0   1.0 0.0 [(0, 0), (1.0, 0.0)]
1   x   x   x   x   x   x   x   0   1   2.0 3.0 [(0, 1), (2.0, 3.0)]
2   x   x   x   x   x   x   x   -1  -2  NaN NaN [(-1, -2)]

This deals with the unequal number of coordinates in each row. Hope that helps!

https://en.xdnf.cn/q/118761.html

Related Q&A

Python: using threads to call subprocess.Popen multiple times

I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they s…

Find a substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

Image processing with single to multiple images

I have an Image showing below: I need to crop the order using python coding. What I need is only the card. So I want to crop the border. How to do it??This is the output I got using the code mentione…

SQLAlchemy Automap not loading table

I am using SQLAlchemy version 2.0.19 (latest public release). I am trying to map existing tables as documented in https://docs.sqlalchemy.org/en/20/orm/extensions/automap.html#basic-use I created a SQL…

Create a base 12 calculator with different limits at diferent digits with python

I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits.Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,"A","B&q…

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: ")) x=0 y=0 z=0while(n>0):x=n%10y=x**3z=z+yn=n//10print (z) #The z here is the same value which I enter, yet it doesnt work. #If I enter 407 as n, z becomes (4…

Python(Scrapy) unpredictable mistake with import load_entry_point

I have such problem, I did nothing with Python or Scrapy, but when I started today my computer I got such error. I have found many different posts and tried some tips and advices, unfortunately, they a…

Debugging RadioButtons program in Python

from Tkinter import *class Application (Frame):def __init__(self, master):Frame.__init__(self, master)self.grid()self.create_widgets()def create_widgets(self):Label(self, text = "Select the last b…

Why am I getting an Internal Server error

My python script runs just fine on the Apache server locally set up on my computer, however, on importing the json2html library I am getting an internal server errorThe moment I comment the import stat…

Save pixel data in txt format in PIL

My program is to extract the pixel from an image and to save the pixel data in the text file for analysis. My picture is a binary image that gives only 255 and 0 sHere is the program:from PIL import Im…