piRSquared piRSquared - 3 months ago 8
Python Question

How do I convert a MultiIndex to type string

consider the MultiIndex

idx


idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)])


When I do

idx.to_series().str.join(' ')


I get

2013 1 NaN
2 NaN
3 NaN
4 NaN
2014 1 NaN
2 NaN
3 NaN
4 NaN
2015 1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64


This happens because the dtypes of the different levels are
int
and not
str
.
join
expects a
str
. How do I convert the whole
idx
to
str
?

I've done

join = lambda x, delim=' ': delim.join([str(y) for y in x])
idx.to_series().apply(join, delim=' ')

2013 1 2013 1
2 2013 2
3 2013 3
4 2013 4
2014 1 2014 1
2 2014 2
3 2014 3
4 2014 4
2015 1 2015 1
2 2015 2
3 2015 3
4 2015 4
dtype: object


I expect there is a simpler way that I'm overlooking.

Answer

I'm not sure it's the most elegant way, but it should work:

idx.get_level_values(0).astype(str).values + ' ' + idx.get_level_values(1).astype(str).values