Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert pandas series to tuple of index and value

I'm looking for an efficient way to convert a series to a tuple of its index with its values.

s = pd.Series([1, 2, 3], ['a', 'b', 'c']) 

I want an array, list, series, some iterable:

[(1, 'a'), (2, 'b'), (3, 'c')] 
like image 508
piRSquared Avatar asked Jul 19 '16 21:07

piRSquared


People also ask

How do you create a tuple series?

Creating a pandas Series from a tuple is similar to creating a Series from a list. Make the tuple which contains the required data, and then pass it to the data parameter of the series constructor.

How do you get items from pandas series?

Accessing Element from Series with Position In order to access the series element refers to the index number. Use the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.

Can you index a pandas series?

The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series. index attribute is used to get or set the index labels of the given Series object.


1 Answers

Well it seems simply zip(s,s.index) works too!

For Python-3.x, we need to wrap it with list -

list(zip(s,s.index)) 

To get a tuple of tuples, use tuple() : tuple(zip(s,s.index)).

Sample run -

In [8]: s Out[8]:  a    1 b    2 c    3 dtype: int64  In [9]: list(zip(s,s.index)) Out[9]: [(1, 'a'), (2, 'b'), (3, 'c')]  In [10]: tuple(zip(s,s.index)) Out[10]: ((1, 'a'), (2, 'b'), (3, 'c')) 
like image 116
Divakar Avatar answered Sep 19 '22 07:09

Divakar