How to access a variable which has a colon in its name in Python?
Question:
I created this code below to extract each individual key as separate data frames. However, since the prim_keys contains colon in their name, e.g. '5091016:2'
, the resulting dataframes should be named something like data5091016:2
. But, it is impossible to access these datafarmes just typing that. How can I access these dataframes?
primkeys = list(data.prim_key.unique())
grouped = data.groupby(['prim_key'])
for i in primkeys:
globals()[f'data{i}'] = grouped.get_group(i)
Thanks already. Best.
Answers:
You can use a dict instead of create dynamically dataframes:
dfs = dict(list(df.groupby('prim_key')))
Now you can use dfs['5091016:2']
.
You can set whatever key you want in globals()
, but if it’s not an identifier (or isn’t even a string!) it isn’t a variable because the language can’t access it (short of manually constructing bytecode objects). If you want to change your keys to be identifiers (beyond prefixing with a letter, as you have already done), go for it.
I created this code below to extract each individual key as separate data frames. However, since the prim_keys contains colon in their name, e.g. '5091016:2'
, the resulting dataframes should be named something like data5091016:2
. But, it is impossible to access these datafarmes just typing that. How can I access these dataframes?
primkeys = list(data.prim_key.unique())
grouped = data.groupby(['prim_key'])
for i in primkeys:
globals()[f'data{i}'] = grouped.get_group(i)
Thanks already. Best.
You can use a dict instead of create dynamically dataframes:
dfs = dict(list(df.groupby('prim_key')))
Now you can use dfs['5091016:2']
.
You can set whatever key you want in globals()
, but if it’s not an identifier (or isn’t even a string!) it isn’t a variable because the language can’t access it (short of manually constructing bytecode objects). If you want to change your keys to be identifiers (beyond prefixing with a letter, as you have already done), go for it.