Open
Description
I usually have to change the value of an element in pd.Index
but it's difficult without the replace
method that is present in pd.Series
. I usually have a bunch of Jupyter
cells depending on a particular pd.DataFrame
or pd.Series
with complicated transformations and a graph at some point. In most cases, I have to change the labels for a few to clean them up for publication quality figures. Currently, I have to use an if else statement with map
method but it would nice to be able to just do replace
.
print(pd.__version__)
print("_________________________")
idx = pd.Index([0,1,2])
Se = pd.Series(list("abc"), index=idx)
# Can do it to pd.Series
print(Se)
print(Se.replace({"b":"replaced_b"}))
# but not pd.Index
print("_________________________")
print(idx)
d = {1:100}
print(idx.map(lambda x: d[x] if x in d else x))
print(idx.replace({1:100}))
# 0.21.1
# _________________________
# 0 a
# 1 b
# 2 c
# dtype: object
# 0 a
# 1 replaced_b
# 2 c
# dtype: object
# _________________________
# Int64Index([0, 1, 2], dtype='int64')
# Int64Index([0, 100, 2], dtype='int64')
# ---------------------------------------------------------------------------
# AttributeError Traceback (most recent call last)
# <ipython-input-383-0b8eacd67c54> in <module>()
# 11 d = {1:100}
# 12 print(idx.map(lambda x: d[x] if x in d else x))
# ---> 13 print(idx.replace({1:100}))
# 14
# AttributeError: 'Int64Index' object has no attribute 'replace'