Home > Net >  Converting list of items in pandas dataframe column to tuples
Converting list of items in pandas dataframe column to tuples

Time:07-09

I have a dataframe that contains list of items like below.

  |  B       |  A         |
   ---------- ------------ 
  |0.07      | [a,b,c]    |
  |0.009     | [d,e,f]    |
  |0.008     | [g,h,j]    |
   ---------- ------------ 

The goal is to convert the list of items present in col A to tuples like below

  |  B       |  A         |
   ---------- ------------ 
  |0.07      | (a,b,c)    |
  |0.009     | (d,e,f)    |
  |0.008     | (g,h,j)    |
   ---------- ------------ 

So how can this be achieved using pandas in python ?

CodePudding user response:

¡Good day!

As @Shubham Sharma mentions in his comment you can solve your problem with the following line of code:

import pandas as pd

columnas=["B" ,"A" ]      
data=[
      [0.07,["a","b","c"]],    
      [0.009,["d","e","f"]],    
      [0.008,["g","h","j"]] 
      ]  
df = pd.DataFrame(data, columns=columnas)
df["A"]=df['A'].map(tuple) 
print(df)

Result:

       B          A
0  0.070  (a, b, c)
1  0.009  (d, e, f)
2  0.008  (g, h, j)
  • Related