Reputation: 4969
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.
Upvotes: 2
Views: 69
Reputation: 25239
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
Upvotes: 5
Reputation: 150735
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
Upvotes: 3