piRSquared piRSquared - 5 days ago 6
Python Question

quickest way to to convert list of tuples to a series

Consider a list of tuples

lst


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


question

What is the quickest way to convert this to the series

i
a 10
b 20
Name: c, dtype: int64


attempts

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


This is inefficient.

Answer

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
Comments