Pandas DataFrame function to_stata() in Python
The Pandas DataFrame function to_stata() used to export DataFrame object to state dta format.
Syntax
 1 DataFrame.to_stata(path, *, convert_dates = None, write_index = True, byteorder = None, time_stamp = None,
 2  data_label = None, variable_labels = None, version = 114, convert_strl = None, compression = 'infer',
 3  storage_options = None, value_labels = None)
path : It is string, path object or buffer that implement a binary write() function.
convert_dates : It is dictionary that mapping column that containing datetime types to stata internal format to use when writing the dates. The options are 'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'.
write_index : It is boolean that write the index to stata dataset.
byteorder : It is string that can be less than or greater than, little or big.
time_stamp : It is datetime to use as file creation date. If not specified the default value will be current time.
data_label : It is string that specifies a label for the data set. It must be 80 chars or smaller.
variable_labels : It is dictionary that contain columns as keys and variable labels as values. The label must be 80 characters or smaller.
version : It can be 114, 117, 118, 119 or None that use in the output dta file. If value is not specified the default value will be 114.
convert_strl : It is list that specifies the column names to convert to string columns to Stata StrL format. It available only with version 117.
compression : It is string or dictionary that specifies on-the-fly compression of the output data. If not specified the default value will be infer.
storage_options : it is a dictionary that specifies the extra options for storage.
value_labels : It is a dictionary of dictionary that contain columns as keys and dictionaries of column value to labels as values. The labels for a single variable must be 32000 characters or smaller.
to_stata() function
 1 import pandas as pd
 2 
 3 df = pd.DataFrame({'C1': ['value 1', 'value 2', 'value 3', 'value 4'],
 4                    'C2': [236, 87, 530, 329]})
 5                    
 6 df.to_stata('dataframe.dta')
 7 print('The dataframe object is written !')
In the above example, a DataFrame object is created by passing a dictionary object. A to_stata() function is called by passing a path that export DataFrame object as dta foramt.

Read stata object

Read stata object
 1 import pandas as pd
 2 
 3 res = pd.read_stata('dataframe.dta')
 4 print('The stata content :')
 5 print(res)
In the above example, a read_stata() function is called by passing a name that read the stata object from the file and assign to the variable that will be printed on console.
Output
 1 The stata content :
 2    index       C1   C2
 3 0      0  value 1  236
 4 1      1  value 2   87
 5 2      2  value 3  530
 6 3      3  value 4  329
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us