2

I have a list that looks like this :

[['a', 'b', 100], ['b', 'c', 200], ['c', 'd', 300]]

And what I want to do is to convert this into Dataframe where index and columns are ['a','b','c','d'] and what I want should look like this:

Desired DataFrame

3
  • 1
    Welcome to Stack Overflow! What code have you tried to make your dataframe so far and what's the output? Commented Mar 24, 2021 at 14:00
  • @BrunoPicasso If you find my solution helpful, I'd appreciate it if you mark it as the correct answer. Thank you! Commented Apr 7, 2021 at 14:24
  • 1
    @Albo Of course! sorry my bad. I'm new here Commented Apr 8, 2021 at 15:44

1 Answer 1

1

With this:

import pandas as pd
import numpy as np

values = [['a', 'b', 100], ['b', 'c', 200], ['c', 'd', 300]]

col_idx = ["a", "b", "c", "d"]
x = [ord(x) - 97 for x, _, _ in values]
y = [ord(y) - 97 for _, y, _ in values]
v = [v for _, _, v in values]
A = np.zeros((len(col_idx), len(col_idx)), dtype=np.int)
A[x, y] = v

df = pd.DataFrame(A.T + A, columns=col_idx, index=col_idx)

you will get df as:

|    |   a |   b |   c |   d |
|:---|----:|----:|----:|----:|
| a  |   0 | 100 |   0 |   0 |
| b  | 100 |   0 | 200 |   0 |
| c  |   0 | 200 |   0 | 300 |
| d  |   0 |   0 | 300 |   0 |
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Here is my solution: ''' w = pd.DataFrame({'nombre': nombre}) w.set_index('nombre', inplace = True) df1 = pd.concat([w, pd.DataFrame(columns = nombre)]) df1 = df1.replace(np.nan, 0) for i in lista: df1[i[0]][i[1]] = i[2] df1[i[1]][i[0]] = i[2] df1''' I have previously defined the names and values via input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.