Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create two different columns from a fixed size tuple in Pandas

My current df looks like below for the column product_pair:

product_pair
---------------------
('B00XA1075Y', 'B002HQCWYM')
('B01G4I8WCE', 'B00H2AAXMQ')
...

I want to create two different columns for the above tuples like below:

product_pair                  |    p1        |   p2     
-----------                     -------       ----------
('B00XA1075Y', 'B002HQCWYM')  | B00XA1075Y   | B002HQCWYM
('B01G4I8WCE', 'B00H2AAXMQ')  | B01G4I8WCE   | B00H2AAXMQ
...

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

import ast
df = pd.concat([df, pd.DataFrame(df['product_pair'].astype(str).apply(ast.literal_eval).tolist(), columns=['p1', 'p2'])], axis=1)

Output:

>>> df
               product_pair          p1          p2
0  (B00XA1075Y, B002HQCWYM)  B00XA1075Y  B002HQCWYM
1  (B01G4I8WCE, B00H2AAXMQ)  B01G4I8WCE  B00H2AAXMQ
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading