5.1 Origin-Python Data Exchange

This folder contains examples showing data exchange between Python (list, dataframe, dictionary) and Origin objects ( workbook, matrixbook, project variables).

DataFrame and Column Format

'''
This sample shows how to set Column Format with DataFrame and from_df, to_df functions.
Make sure you've installed pandas. To install the module, 
open the Script Window (Shift+Alt+3), type the following and press Enter:
 pip install pandas

The following will check and install:
 pip -chk pandas
'''
import originpro as op
import pandas as pd

# Create a dataframe to fill the sheet
df = pd.DataFrame({
    'Date': ['10/25/2018','02/21/2019','04/01/2020'],
    'Gender':['Male','Male','Female'],
    'Score': [75.5, 86.7, 91],
})

df['Date'] = pd.to_datetime(df['Date'])
df['Gender']= pd.Categorical(df['Gender'])

wks=op.new_sheet()
wks.from_df(df)

#can also create book and get first sheet like this
wks2=op.new_book('w', 'Copy using DF')[0]

#column formats like date is automatically handled
df1=wks.to_df()
wks2.from_df(df1)

Get Tree in Origin as dict

'''
To show how to get a Tree in Origin. 
Tree variables are used extensively inside Origin. In this example, we use an X-Function
which will generate a Tree after its execution. The Tree will have the same name as the 
X-Function, which in the sample below is "fitlr". It does a simple linear fit and generates
basic stats fromt the fit, see
https://www.originlab.com/doc/X-Function/ref/fitLR
'''
import originpro as op
fn=op.path('e') + 'Samples\Curve Fitting\Linear Fit.dat'
wks = op.new_sheet()
wks.from_file(fn,False)
#fit A(x) D(y)
wks.get_book().lt_exec('fitlr (A,D)')
dd = op.lt_tree_to_dict('fitlr')
slope = dd['b']
err = dd['berr']
print(f'slope= {slope:.3f} +- {err:.3f}')

Matrix Data Exchange

'''This example transfers a 3D Numpy array (four 3X3 matrices) into Origin,
the data is saved into a matrix sheet containing four matrix objects. Then
the data is extracted from the matrix sheet and saved into Numpy arrays. '''
import numpy as np
import originpro as op

arr=np.random.rand(4,3,3)

mxs=op.new_sheet('m')
mxs.from_np(arr)
mxs.show_thumbnails()

# Extract the data from the four matrix objects and save into a Numpy 3D array.
arr_3d=mxs.to_np3d()
print(arr_3d.shape)

# Extract the data from the first matrix object and save into a Numpy 2D array.
arr_2d=mxs.to_np2d(0)
print(arr_2d.shape)

Putting Data to Columns

'''
This sample shows how to use from_list function to put data to Columns
'''
import originpro as op

# Prepare data.
data=[x/10. for x in range(50)]

# Prepare worksheet.
wks=op.new_sheet()

# Put data to col(A), and set Long Name, Units, designation as well
wks.from_list('A',data, 'time', 'sec',axis='N')

# Prepare data and out data to col(B)
data1=[x*1.5 for x in range(50)]
wks.from_list('B', data1, axis='X')

# Add a third column
wks.cols=3

# Use the sum of data and data1 to set the third column
wks.from_list(2, [sum(i) for i in zip(data, data1)], comments = 'A+B')

Worksheet User Tree Access

'''
This sample shows how to prepare a worksheet tree, and 
how to read the values back. This is useful to save the metadata
of a data file. See the blog:
https://blog.originlab.com/accessing-metadata-using-python
'''

import originpro as op

# Create a new worksheet and set worksheet tree values.
wks = op.new_sheet()
wks.set_str("tree.data.name", "Larry")
wks.set_int("tree.data.age", 37)
wks.set_float("tree.data.mean", 23.56)

# access the tree as a dictionary
dd = wks.userprops['data']
user=dd['name']
value=dd['age']
print(f'{user} is {value}')

# you can also get the tree as an xml ElementTree for more advanced usage
trWks = wks.usertree
trData = trWks.find('data')
for child in trData:
    print(f'{child.tag} = {child.text}')
    
# how to put a modified tree to another sheet
wk2 = op.new_sheet()
age_node=trData.find('age')
age_node.text='47'

wk2.usertree=trWks
print(wk2.userprops['data']['age'])