How do i convert a Python Pandas Dataframe to Matlab types?

조회 수: 397 (최근 30일)
Ricardo Alves
Ricardo Alves 2016년 5월 17일
답변: Francesco Giaretta 2024년 2월 1일
I am calling a python function from Matlab code which returns a Pandas Dataframe. I would like to convert the content of the DataFrame to Matlab data types, but I can't find the correct way to do it. Thanks in advance for any help on this.

답변 (6개)

Todd Leonhardt
Todd Leonhardt 2016년 5월 18일
A simple and effective, but perhaps inelegant, solution is to first save the Pandas DataFrame as a CSV file and then read that data into MATLAB as a table datatype (as long as you have MATLAB R2013b or newer).
You can save a Pandas DataFrame as a CSV file with the DataFrame.to_csv() function: http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.DataFrame.to_csv.html
You can read a CSV file into MATLAB as a table using the readtable() function: http://www.mathworks.com/help/matlab/ref/readtable.html

Todd Leonhardt
Todd Leonhardt 2016년 5월 18일
편집: Todd Leonhardt 2016년 5월 18일
Another possibility is to convert the Pandas DataFrame to a Python dictionary using the DataFrame.to_dict() method: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html
Once you have the data as a Python Dictionary, you should be able to a use that in MATLAB as shown here: http://www.mathworks.com/help/matlab/matlab_external/use-python-dict-type-in-matlab.html

Jeffrey Daniels
Jeffrey Daniels 2018년 10월 19일
편집: Jeffrey Daniels 2019년 11월 1일
I solved this problem by querying the Pandas dataframe column data types and inserting them as the last row of the dataframe, convert the df to string and pass to Matlab. Then once in Matlab I have a method that reads the string into a Matlab table and applies the data type specified in the last row of the CSV to each column of the table. It's not elegant, but it is fairly bulletproof. This method works completely in memory space and does not require writing to hard drive.
  댓글 수: 1
Dev-iL
Dev-iL 2020년 5월 6일
Would it be possible for you to post a code sample? There are several moving parts in this solution...

댓글을 달려면 로그인하십시오.


Artem Lensky
Artem Lensky 2022년 5월 25일
It implements two funcions:
  • df2t - that converts Pandas DataFrame to Matlab Table
  • t2df - that converts Matlab Table to Pandas DataFrame.
The examples are shown in test.mlx.

Bryan Yu
Bryan Yu 2017년 12월 1일
HDF5 is native for both pandas and MATLAB. Could be a good compromise for speed and type safety.

Francesco Giaretta
Francesco Giaretta 2024년 2월 1일

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by