Skip to content

Instantly share code, notes, and snippets.

@KeAWang
Created May 16, 2023 22:57
Show Gist options
  • Save KeAWang/9a42fb50b3c42ea0a4a158edae86a33d to your computer and use it in GitHub Desktop.
Save KeAWang/9a42fb50b3c42ea0a4a158edae86a33d to your computer and use it in GitHub Desktop.
Multidimensional array to pandas dataframe
import pandas as pd
from typing import Optional, List
def array_to_dataframe(array, axis_names: Optional[List[str]]=None):
"""Based on https://stackoverflow.com/questions/35525028/how-to-transform-a-3d-arrays-into-a-dataframe-in-python"""
if axis_names is None:
axis_names = list(range(array.ndim))
index = pd.MultiIndex.from_product([range(s) for s in array.shape], names=names)
df = pd.DataFrame({"array": array.flatten()}, index=index)["array"]
return df
if __name__ == "__main__":
import numpy as np
x = np.random.randn((2,3,4))
array_to_dataframe(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment