piRSquared - 9 months ago 45

Python Question

Consider a list of tuples

`lst`

`lst = [('a', 10), ('b', 20)]`

What is the quickest way to convert this to the series

`i`

a 10

b 20

Name: c, dtype: int64

`pd.DataFrame(lst, list('ic')).set_index('i').c`

This is inefficient.

Answer Source

One approach with `NumPy`

assuming regular length list -

```
arr = np.asarray(lst)
out = pd.Series(arr[:,1], index = arr[:,0])
```

Sample run -

```
In [147]: lst = [('a', 10), ('b', 20), ('j',1000)]
In [148]: arr = np.asarray(lst)
In [149]: pd.Series(arr[:,1], index = arr[:,0])
Out[149]:
a 10
b 20
j 1000
dtype: object
```