Nirali Khoda
Nirali Khoda

Reputation: 1691

convert list of tuples into single column of pandas dataframe?

I have a list of tuple like this :

list_t = [(1,2),(1,7),(1,8),(2,6),(5,8)]

I want to make data frame out this but just one column:

enter image description here

Currently using this

df_com = pd.DataFrame(list_t,columns=["so","des"])

but then I have to join them again so operation cost is increased.

Thank you for your help

Upvotes: 3

Views: 2038

Answers (3)

David Meu
David Meu

Reputation: 1545

Why not converting each to str:

import pandas as pd
list_t = [(1,2),(1,7),(1,8),(2,6),(5,8)]
list_t = [str(item) for item in list_t]
df_com = pd.DataFrame(list_t,columns=["tuples"])
print(df_com)

Output:

   tuples
0  (1, 2)
1  (1, 7)
2  (1, 8)
3  (2, 6)
4  (5, 8)

Just a note that this is faster from above

(although it is 'elegant'):

timeit("""import pandas as pd;list_t=[(1,2),(1,7),(1,8),(2,6),(5,8)];pd.Series(list_t).to_frame('new');""",number=1000)
     0.25547240000014426
timeit("""import pandas as pd;list_t=[(1,2),(1,7),(1,8),(2,6),(5,8)];pd.DataFrame({'tuple': list_t});""",number=1000)
     0.19921229999999923

Current answer:

timeit("""import pandas as pd;list_t=[(1,2),(1,7),(1,8),(2,6),(5,8)];list_t = [str(item) for item in list_t];pd.DataFrame(list_t,columns=["tuples"]);""",number=1000)
0.144553399999495

Upvotes: 2

piRSquared
piRSquared

Reputation: 294238

Pass a dict to the DataFrame constructor.

pd.DataFrame({'tuple': list_t})

    tuple
0  (1, 2)
1  (1, 7)
2  (1, 8)
3  (2, 6)
4  (5, 8)

Upvotes: 4

jezrael
jezrael

Reputation: 862581

Convert list of tuples to Series:

s = pd.Series(list_t)
print (s)
0    (1, 2)
1    (1, 7)
2    (1, 8)
3    (2, 6)
4    (5, 8)
dtype: object

For DataFrame add Series.to_frame:

df = pd.Series(list_t).to_frame('new')
print (df)
      new
0  (1, 2)
1  (1, 7)
2  (1, 8)
3  (2, 6)
4  (5, 8)

Upvotes: 6

Related Questions