piRSquared piRSquared - 1 year ago 77
Python Question

quickest way to to convert list of tuples to a series

Consider a list of tuples


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


What is the quickest way to convert this to the series

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])
a      10
b      20
j    1000
dtype: object
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download