0
list=[['10, 0.01, 0.0428, 120; 30, 0.1, 2, 33; 50, 0.023, 0.31, 0.65'],
      ['10, 0.7, 0.5428, 2.31'],
      ['50, 0.3, 0.35, 0.1'],
      ['-10, 0.2, 0.048, 124; -30, 0.11, 24, 3; -50, 0.02, 0.1, 0.60; 0, 0, 0, 0; 10, 0.1, 2, 33; 
       20, 0.023, 0.31, 0.66']]

df=pd.DataFrame(list)

I have a dataframe df from which I am trying to get the 3rd value after each semicolon sign if the column name matches with the 1st value after the semicolon sign. The expected output is as below. Any clue on how to tackle this in a simple way?

enter image description here

7
  • 1
    There's no semicolon in the 2nd and 3rd rows. Commented Oct 4, 2021 at 19:43
  • In that case simply need to take 3rd value Commented Oct 4, 2021 at 19:44
  • 2
    How did you get this list? Yes you can parse the floats, but you probably want to fix the source Commented Oct 4, 2021 at 19:45
  • I don't think I understand the question ? Commented Oct 4, 2021 at 19:45
  • @juanpa.arrivillaga the actual data is a dataframe of 1000s of rows saved locally on my system, i have replicated a few rows in a list so people can copy and try on their system Commented Oct 4, 2021 at 19:48

1 Answer 1

1

Use nested loops:

d = {}
for r, i in enumerate(l):
    for j in i[0].split(';'):
        k = j.split(',')
        c, v = int(k[0]), float(k[2])
        d[(r, c)] = v

df = pd.Series(d).unstack(fill_value=0)

Output:

>>> df
   -50   -30    -10   0       10    20   30    50
0  0.0   0.0  0.000  0.0  0.0428  0.00  2.0  0.31
1  0.0   0.0  0.000  0.0  0.5428  0.00  0.0  0.00
2  0.0   0.0  0.000  0.0  0.0000  0.00  0.0  0.35
3  0.1  24.0  0.048  0.0  2.0000  0.31  0.0  0.00
Sign up to request clarification or add additional context in comments.

6 Comments

OP wants the third item, which is k[2]!
@ddejohn You really pay more attention than me :) Thanks.
@RahulKumar. I updated my answer. Can you check it please?
You always answer a hair faster than me lol, it's the least I can do to get back at you for beating me to the punch.
@ddejohn. I will not do it again, I promise :)
|

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.