Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace the values of nested lists stored in python dataframe?

I have the following dataframe

data = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]]]

df = pd.DataFrame(data)

Also, I have a second dataframe df2:

data2 = [[1, 10], [1, 15], [1, 14], [1, 20], [1, 18]]
df2 = pd.DataFrame(data2, columns=['dir', 'line'])

The values of the nested lists of df represent the Index of df2. I would like to replace the values of the nested lists of df with the values of the column line of df2. The expected output is the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

finalData = [[[[[15, 14, 10], [15]],[[15, 14], [20]]],
        [[[[15, 14], [20]]]], [[[15]]]], [[[[15, 14, 10], [15]],[[15, 14], [20]]],
        [[[[15, 14], [29]]]], [[[15]]]]]

finaldf = pd.DataFrame(finalData)

>Solution :

Here you are.

data = [[[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]], [[[[1, 2, 0], [1]],[[1, 2], [4]]],
        [[[[1, 2], [4]]]], [[[1]]]]]
df = pd.DataFrame(data)
data2 = [[1, 10], [1, 15], [1, 14], [1, 20], [1, 18]]
df2 = pd.DataFrame(data2, columns=['dir', 'line'])

def fn(index):
    if isinstance(index, list):
        return [fn(i) for i in index]
    else:
        return df2['line'][index]

final = df.applymap(fn)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading