To create a 3D Pandas DataFrame, you can use a combination of the pd.Panel and pd.DataFrame objects. Here’s an example of how you can create a 3D DataFrame:
import pandas as pd import numpy as np # Create a 3D numpy array data = np.random.randn(2, 3, 4) # Create a panel with the 3D numpy array panel = pd.Panel(data) # Convert the panel to a 3D DataFrame df = panel.to_frame() # Print the resulting DataFrame print(df)
In this example, we first create a 3D numpy array using the np.random.randn function. We then create a Pandas panel object using this numpy array, and convert it to a 3D DataFrame using the to_frame() method. Finally, we print the resulting DataFrame.
import pandas as pd import numpy as np # Create a 3D numpy array data = np.random.randn(2, 3, 4) # Create a MultiIndex idx = pd.MultiIndex.from_product([range(s) for s in data.shape], names=['x', 'y', 'z']) # Create a DataFrame with the 3D numpy array and the MultiIndex df = pd.DataFrame({'value': data.flatten()}, index=idx) # Print the resulting DataFrame print(df)
In this example, we first create a 3D numpy array as before. We then create a MultiIndex using the pd.MultiIndex.from_product method, specifying the range of values for each dimension and giving them appropriate names. Finally, we create a DataFrame with the flattened numpy array and the MultiIndex, which gives us a 3D DataFrame.
1 thought on “How to Create a 3D Pandas DataFrame”