jekwatt / idiomatic_pandas

Tips and tricks for the most common data handling task with pandas.
0 stars 0 forks source link

Tuple unpacking #23

Open jekwatt opened 2 years ago

jekwatt commented 2 years ago

Answers from Cameron:

Using operator itemgetter:

>>> s = pd.Series([(1,"a"), (2,"b")], name="col1")
>>> df = s.to_frame()
>>>df["col1"].apply(itemgetter(0))
0    1
1    2
Name: col1, dtype: int64

>>>df["col1"].apply(itemgetter(1))
0    a
1    b
Name: col1, dtype: object

That definitely works! You can also use the `.str` accessor to do this too:

>>> s = pd.Series([(1,"a"), (2,"b")])
>>> s.str.get(0)
0 1
1 2
dtype: int64

>>> s.str.get(1)
0 a
1 b
dtype: object

Alternatively, you can explode our these values to work with them in a different way.
>>> s.explode()
0 1
0 a
1 2
1 b
dtype: object