arrays into pandas dataframe columns
A possible solution could be transposing
and renaming the columns after transforming the numpy
array into a dataframe
. Here is the code:
import numpy as npimport pandas as pdframe = [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4]]numpy_data= np.array(frame)#transposing laterdf = pd.DataFrame(data=numpy_data).T #creating a list of columns using list comprehension without specifying number of columnsdf.columns = [f'mycol{i}' for i in range(0,len(df.T))] print(df)
Output:
mycol0 mycol1 mycol2 mycol30 0 0 1 21 1 0 3 42 0 0 3 4
Same code for 11 columns:
import numpy as npimport pandas as pdframe = [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4], [5, 2, 2], [6,7,8], [8,9,19] , [10,2,4], [2,6,5], [10,2,5], [11,2,9]]numpy_data= np.array(frame)df = pd.DataFrame(data=numpy_data).Tdf.columns = [f'mycol{i}' for i in range(0,len(df.T))]print(df)
mycol0 mycol1 mycol2 mycol3 mycol4 mycol5 mycol6 mycol7 mycol8 mycol9 mycol100 0 0 1 2 5 6 8 10 2 10 111 1 0 3 4 2 7 9 2 6 2 22 0 0 3 4 2 8 19 4 5 5 9
You can transpose
the array and add_prefix
frame = [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4]]pd.DataFrame(np.array(frame).T).add_prefix('column')
Out:
column0 column1 column2 column30 0 0 1 21 1 0 3 42 0 0 3 4
Works with every number of arrays
frame = [[0, 1, 0], [0, 0, 0], [1, 3, 3], [2, 4, 4], [1,0,1], [2,0,3]]pd.DataFrame(np.array(frame).T).add_prefix('column')
Out:
column0 column1 column2 column3 column4 column50 0 0 1 2 1 21 1 0 3 4 0 02 0 0 3 4 1 3
One way may be change it to dictionary with column name by iterating each item in the list as below:
df = pd.DataFrame({'column{}'.format(index):i for index, i in enumerate(frame)})
Alternatively, other way may be to use transpose
to what you already have. For column names you can exclude on creating dataframe and add later (not sure if you need numpy
):
df = pd.DataFrame(data=frame)df = df.T # transposingdf.columns = ['column{}'.format(i+1) for i in df.columns] # adding column names
Result (either way):
column1 column2 column3 column40 0 0 1 21 1 0 3 42 0 0 3 4