w3resource

Pandas DataFrame: to_stata() function

DataFrame - to_stata() function

The to_stata() function is used to export DataFrame object to Stata dta format.

Writes the DataFrame to a Stata dataset file.

Syntax:

DataFrame.to_stata(self, fname, convert_dates=None, write_index=True, encoding='latin-1', byteorder=None, time_stamp=None, data_label=None, variable_labels=None, version=114, convert_strl=None)

Parameters:

Name Description Type / Default Value Required / Optional
fname  String, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary write() function. If using a buffer then the buffer will not be automatically closed after the file data has been written. str, buffer or path object Required
convert_dates   Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are ‘tc’, ‘td’, ‘tm’, ‘tw’, ‘th’, ‘tq’, ‘ty’. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to ‘tc’. Raises NotImplementedError if a datetime column has timezone information. dict Required
write_index Write the index to Stata dataset. bool Required
encoding Default is latin-1. Unicode is not supported. str Required
byteorder Can be “>”, “<”, “little”, or “big”. default is sys.byteorder. str Required
time_stamp A datetime to use as file creation date. Default is the current time. datetime Required
data_label A label for the data set. Must be 80 characters or smaller. str Optional
variable_labels Dictionary containing columns as keys and variable labels as values. Each label must be 80 characters or smaller. dict Required
version Version to use in the output dta file. Version 114 can be used read by Stata 10 and later. Version 117 can be read by Stata 13 or later. Version 114 limits string variables to 244 characters or fewer while 117 allows strings with lengths up to 2,000,000 characters. {114, 117}
Default Value: 114
Required
convert_strl List of column names to convert to string columns to Stata StrL format. Only available if version is 117. Storing strings in the StrL format can produce smaller dta files if strings have more than 8 characters and values are repeated. list Optional

Raises: NotImplementedError

  • If datetimes contain timezone information
  • Column dtype is not representable in Stata

  • ValueError
  • Columns listed in convert_dates are neither datetime64[ns] or datetime.datetime
  • Column listed in convert_dates is not in DataFrame
  • Categorical label contains more than 32,000 characters

Example:


Download the Pandas DataFrame Notebooks from here.

Previous: DataFrame - to_latex() function
Next: DataFrame - to_records() function



Share this Tutorial / Exercise on : Facebook and Twitter