You can combine Pandas dataframes and Numpy Matrices by using the pd.concat()
function in Pandas.
pd.concat([df,pd.DataFrame(Matrix)],axis=1)
The following are the steps to combine Pandas dataframe and Numpy matrix.
Step 1: Generate a dataframe
The following is to generate a dataframe and a matrix first.
# Generate a dataframe
car_data = {'Brand': ['Tesla', 'Tesla','Tesla','Ford'],
'Location': ['CA', 'CA','NY','MA'],
'Year':[2019,2018,2020,2019]}
car_data=pd.DataFrame(data=car_data)
# print out the dataframe
print('Dataframe: \n',car_data)
The following is the print out of the dataframe.
Dataframe: Brand Location Year 0 Tesla CA 2019 1 Tesla CA 2018 2 Tesla NY 2020 3 Ford MA 2019
Step 2: Generate a matrix
# Generate a matrix
mt_1=np.matrix([[88,33,44,55],[4,2,3,5]])
mt_1_T=mt_1.transpose()
# print out the matrix
print('Generated Matrix:\n',mt_1_T)
The following is the print out of the generated matrix.
Generated Matrix: [[88 4] [33 2] [44 3] [55 5]]
Step 3: Combine Pandas dataframe and Numpy Matrix
The following is the Python code combining a dataframe and a matrix.
# Combine the dataframe and the matrix
df_combined=pd.concat([car_data,pd.DataFrame(mt_1_T)],axis=1)
print(df_combined)
The following is the combined dataframe-a combinatino of the original dataframe and the matrix.
Brand Location Year 0 1 0 Tesla CA 2019 88 4 1 Tesla CA 2018 33 2 2 Tesla NY 2020 44 3 3 Ford MA 2019 55 5