how to convert a dataframe to numpy array code example

Example 1: make pandas df from np array

numpy_data = np.array([[1, 2], [3, 4]])
df = pd.DataFrame(data=numpy_data, index=["row1", "row2"], columns=["column1", "column2"])
print(df)
>>>
  column1  column2
row1        1        2
row2        3        4

Example 2: convert dataframe to numpy array

>>> pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()
array([[1, 3],
       [2, 4]])

Example 3: numpy arrauy to df

numpy_data = np.array([[1, 2], [3, 4]])
df = pd.DataFrame(data=numpy_data, index=["row1", "row2"], columns=["column1", "column2"])
print(df)