Mdhale Mdhale - 1 month ago 5
Python Question

Creating a pandas dataframe by adding columns

Is there a way to create a dataframe by adding individual columns?

Following is my code snippet:

df=pandas.DataFrame()
for key in matrix:
for beta in matrix[key]:
df[key] = matrix[key][beta]
print(df)


As you can see that I start by creating an empty dataframe and then as my loop iterates, I am attempting to add a new column.
This adds the column names but doesn't add values to the rows.

Note matrix is a multi-level hash

{'ABC10059536': {'577908224': '0.5902'},
'ABC10799208': {'577908224': '0.369'},
'ABC12564102': {'577908224': '0.163'},
'ABC17441804': {'577908224': '0.4233'},
'ABC20764275': {'577908224': '0.349'},
'ABC21090866': {'577908224': '0.4704'}}

Answer

I think you can use DataFrame constructor:

d = {'ABC10059536': {'577908224': '0.5902'},
  'ABC10799208': {'577908224': '0.369'},
  'ABC12564102': {'577908224': '0.163'},
  'ABC17441804': {'577908224': '0.4233'},
  'ABC20764275': {'577908224': '0.349'},
  'ABC21090866': {'577908224': '0.4704'}}

df = pd.DataFrame(d) 
print (df)  
          ABC10059536 ABC10799208 ABC12564102 ABC17441804 ABC20764275  \
577908224      0.5902       0.369       0.163      0.4233       0.349   

          ABC21090866  
577908224      0.4704