2

I have a list as such:

[[None, 'ASK', 'BID'], ['4Y', 343.545, 344.621],['7Y', 0.016, 0.015],['9Y', 99.9, 99.8]]

and I would like to convert that into a dataframe as such:

'4Y' | 'ASK' | 343.545 '4Y' | 'BID' | 344.621 '7Y' | 'ASK' | 0.016 '7Y' | 'BID' | 0.015 '9Y' | 'ASK' | 99.9 '9Y' | 'BID' | 99.8

I've tried all sorts of "loopy" ways, but they seem terribly ugly and inefficient.

5
  • 1
    what's wrong with pd.DataFrame(the_array)? Commented Nov 21, 2019 at 17:38
  • how about that it doesn't produce the expected outcome for a candidate, mate? Commented Nov 21, 2019 at 17:42
  • Does any sublist can have None? Commented Nov 21, 2019 at 17:43
  • @DanielMesejo No, None is present only as the 0th element of the 0th sublist. Commented Nov 21, 2019 at 17:44
  • I don't think this question deserve downvoting. Someone may disagree with me. I give this an upvote to counteract the downvoting. Commented Nov 21, 2019 at 17:59

2 Answers 2

5

Assume l is your list. Construct df and melt

df = pd.DataFrame(l[1:], columns=l[0])
df.rename({None: 'Year'}, axis=1).melt('Year').sort_values('Year')

Out[477]:
  Year variable    value
0   4Y      ASK  343.545
3   4Y      BID  344.621
1   7Y      ASK    0.016
4   7Y      BID    0.015
2   9Y      ASK   99.900
5   9Y      BID   99.800
Sign up to request clarification or add additional context in comments.

Comments

3

Takse some time to see what you want:

arr[0][0] = 'idx'
(pd.DataFrame(arr[1:], columns=arr[0])
   .set_index('idx')
   .stack()
   .reset_index(name='value')
)

Output:

  idx level_1    value
0  4Y     ASK  343.545
1  4Y     BID  344.621
2  7Y     ASK    0.016
3  7Y     BID    0.015
4  9Y     ASK   99.900
5  9Y     BID   99.800

1 Comment

who said I downvoted? Not to mention that your question provide minimal information. You could have explained the out put.

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.