Pythonnet System.Object[,] to Pandas DataFrame or Numpy Array

1.6k Views Asked by At

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.

2

There are 2 best solutions below

1
Claudio Cuevas Pazos On BEST ANSWER
pd.DataFrame([[obj[j, i] for j in range(obj.GetLength(1))] for i in range(obj.GetLength(0))])
0
cabo On

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))