Translating pandas.Index
types#
NOTE: For convenience, we’ll use a dummy fetcher used for testing to generate translation data instead of fetching real translations. Generated data is on the form <placeholder-name>-of-<id>
, eg 'placeholder0-of-id0'
.
Since we use fmt='{x}, {y}'
, translated values will take form 'x-of-<id>, y-of-<id>'
.
[1]:
from id_translation import Translator
t = Translator(fmt="{x}, {y}")
/tmp/ipykernel_8364/1782748667.py:3: UserWarning: No fetcher given. Translation data will be automatically generated.
t = Translator(fmt="{x}, {y}")
Dummy data#
[2]:
import pandas as pd
df = pd.DataFrame(
[
["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"],
],
index=[f"idx{i}" for i in range(3)],
)
df.index.name = "name"
df
[2]:
0 | 1 | 2 | 3 | |
---|---|---|---|---|
name | ||||
idx0 | 00 | 01 | 02 | 03 |
idx1 | 10 | 11 | 12 | 13 |
idx2 | 20 | 21 | 22 | 23 |
Translation#
We gave the Index
a name, which will be used unless the names
-argument is given.
By default, DataFrame.columns
are used as the names. As such, translating column values before the DataFrame
itself may break the built-in logic.
[3]:
t.translate(df, inplace=True)
df.columns = t.translate(df.columns, names="name-of-columns")
df.index = t.translate(df.index, fmt="{id}:{name}")
df
[3]:
x-of-0, y-of-0 | x-of-1, y-of-1 | x-of-2, y-of-2 | x-of-3, y-of-3 | |
---|---|---|---|---|
name | ||||
idx0:name-of-idx0 | x-of-00, y-of-00 | x-of-01, y-of-01 | x-of-02, y-of-02 | x-of-03, y-of-03 |
idx1:name-of-idx1 | x-of-10, y-of-10 | x-of-11, y-of-11 | x-of-12, y-of-12 | x-of-13, y-of-13 |
idx2:name-of-idx2 | x-of-20, y-of-20 | x-of-21, y-of-21 | x-of-22, y-of-22 | x-of-23, y-of-23 |
The columns don’t have a name, so one must be given to translate them. Pandas columns are regular indexes, and can have names just like any other index can.
[ ]: