I have the following dictionary:
dict = {(0, 6): array([[1, 2, 3, 0, 1 ,1]]), (0, 9): array([[1, 2, 3, 0, 1, 1]])}
I would like to convert it to a pandas dataframe that looks like this:
Key | v1 | v2 | v3 | v4 | v5 | v6 |
---|---|---|---|---|---|---|
(0,6) | 1 | 2 | 3 | 0 | 1 | 1 |
(0,9) | 1 | 2 | 3 | 0 | 1 | 1 |
I do not want the key to be the index.
Thanks for your help.
CodePudding user response:
Use:
d = {(0, 6): np.array([[1, 2, 3, 0, 1 ,1]]),
(0, 9): np.array([[1, 2, 3, 0, 1, 1]])}
df = pd.DataFrame.from_dict({k: v[0] for k, v in d.items()}, orient='index')
df = df.rename_axis('Key').rename(columns=lambda x: f'v{x 1}').reset_index()
print (df)
Key v1 v2 v3 v4 v5 v6
0 (0, 6) 1 2 3 0 1 1
1 (0, 9) 1 2 3 0 1 1
Or:
df = pd.DataFrame(np.vstack(list(d.values()))).rename(columns=lambda x: f'v{x 1}')
df.insert(0,'Key',list(d.keys()))
print (df)
Key v1 v2 v3 v4 v5 v6
0 (0, 6) 1 2 3 0 1 1
1 (0, 9) 1 2 3 0 1 1