3

I am using Pythonnet to call a C# function which returns a clr Object ( an n x m matrix). In python the type is System.Object[,]. How can I convert this variable to a Pandas DataFrame or something more manageable?

Thank you.

denfromufa
  • 5,610
  • 13
  • 81
  • 138
cabo
  • 127
  • 1
  • 9

2 Answers2

2
pd.DataFrame([[obj[j, i] for j in range(obj.GetLength(1))] for i in range(obj.GetLength(0))])
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep May 07 '19 at 17:37
1

At the end the only solution I could come up is to crawl it until getting an IndexError like this:

import pandas as pd
def ObjectToDataFrame_nx2(obj)
 ts=pd.DataFrame(columns=['Dim1','Dim2'])
 i=0
 while True:
  try:
    dim1=obj[i,0]
    dim2=obj[i,1]
  except IndexError:
    break
  ts=ts.append({'Dim1': dim1, 'Dim2': dim2},ignore_index=True)
  i+=1
 return(ts)

Edit: this is the n x m version

def ObjectToDataFrame_nxm(obj):
    i=0
    vvec=[]
    while True:
        j=0
        vec=[]
        try:
            while True:
                try:
                    vec.append(obj[i,j])
                except IndexError:
                    break
                j+=1
            dummy = obj[i,0]
            vvec.append(vec)
        except IndexError:
            break
        i+=1
    return(pd.DataFrame(vvec))
cabo
  • 127
  • 1
  • 9