1

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'}}
5
  • Can you add sample of matrix - 5,6 keys? Commented Oct 14, 2016 at 20:20
  • Because I believe there is same better and faster way for creating DataFrame as loop Commented Oct 14, 2016 at 20:21
  • I understand but I am using matrix for another part of the code and wanted to create this dataFrame too. Looping gives me one column each time. Check to snippet of matrix. It should create one row with ABC* as column names Commented Oct 14, 2016 at 20:27
  • Please check my solution, I am not sure if you can use it. But maybe you use complicated matrix, so you can update sample. Commented Oct 14, 2016 at 20:40
  • You Sir are simply amazing :) Commented Oct 14, 2016 at 20:49

1 Answer 1

1

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  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.