OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Turn a list of tuples into pandas dataframe with single column

  • Thread starter Thread starter Emi OB
  • Start date Start date
E

Emi OB

Guest
I have a list of tuples like:

Code:
tuple_lst = [('foo', 'bar'), ('bar', 'foo'), ('ping', 'pong'), ('pong', 'ping')]

And I want to create a Dataframe with one column containing each tuple pair, like:

Code:
|     one col       |
|     --------      |
|  ('foo', 'bar')   |
|  ('bar', 'foo')   |
|  ('ping', 'pong') |
|  ('pong', 'ping') |

I tried:

Code:
df = pd.DataFrame(tuple_lst, columns='one col')

But this throws an error as it's trying to split the tuples into 2 separate columns. I know if I pass a list of 2 column names here, it would produce a dataframe with 2 columns which is not what I want. I guess I could then put these two columns back together into a list of tuples, but this feels like a lot of work to break them up and put them back together, I feel there must be a simpler way to do this? I need the output to be a dataframe not a series so I can add other columns etc later on.
<p>I have a list of tuples like:</p>
<pre><code>tuple_lst = [('foo', 'bar'), ('bar', 'foo'), ('ping', 'pong'), ('pong', 'ping')]
</code></pre>
<p>And I want to create a Dataframe with one column containing each tuple pair, like:</p>
<pre><code>| one col |
| -------- |
| ('foo', 'bar') |
| ('bar', 'foo') |
| ('ping', 'pong') |
| ('pong', 'ping') |
</code></pre>
<p>I tried:</p>
<pre><code>df = pd.DataFrame(tuple_lst, columns='one col')
</code></pre>
<p>But this throws an error as it's trying to split the tuples into 2 separate columns. I know if I pass a list of 2 column names here, it would produce a dataframe with 2 columns which is not what I want. I guess I could then put these two columns back together into a list of tuples, but this feels like a lot of work to break them up and put them back together, I feel there must be a simpler way to do this? I need the output to be a dataframe not a series so I can add other columns etc later on.</p>
 

Latest posts

D
Replies
0
Views
1
Dhanushka Amarakoon
D
S
Replies
0
Views
1
Shikhar Ambashta
S
Top