I have a dataframe which looks like this:
key text
0 title Lorem ipsum
1 header Lorem ipsum
2 description Lorem ipsum
.
.
.
.
10 pyramid.male Lorem ipsum
11 pyramid.male_surplus Lorem ipsum
12 pyramid.female Lorem ipsum
13 pyramid.female_surplus Lorem ipsum
.
.
.
.
29 jitterplot.title1 Lorem ipsum
30 jitterplot.metric_1.label Lorem ipsum
31 jitterplot.metric_1.tooltip Lorem ipsum
32 jitterplot.metric_2.label Lorem ipsum
33 jitterplot.metric_2.tooltip Lorem ipsum
The keys represent keys in a JSON file. The JSON structure should look like the following:
{
"title": "Lorem ipsum",
"header": "Lorem ipsum",
"description": "Lorem ipsum",
"pyramid": {
"male": "Lorem ipsum",
"male_surplus": "Lorem ipsum",
"female": "Lorem ipsum",
"female_surplus": "Lorem ipsum"
},
"jitterplot": {
"title1": "Lorem ipsum",
"metric_1": {
"label": "Lorem ipsum",
"tooltip": "Lorem ipsum"
},
"metric_2": {
"label": "Lorem ipsum",
"tooltip": "Lorem ipsum"
}
}
}
Meaning, a . in the key column represents a nested level.
Is there a 'Pythonic' way to achieve this? Currently, I'm just hacking it by manually writing each row to a text file with a custom parser I wrote. But obviously this is not very scalable.
I've prepared a sample CSV which you can read, and added some additional columns if they help. Use the following code:
import pandas as pd
url = 'https://raw.githubusercontent.com/Thevesh/Display/master/i18n_sample.csv'
df = pd.read_csv(url)
df['n_levels'] = df['key'].str.count('\.') # column with number of levels
max_levels = df.n_levels.max() #
df = df.join(df['key'].str.split('.',expand=True))
df.columns = list(df.columns)[:-max_levels-1] + ['key_' + str(x) for x in range(max_levels+1)]