preloader
Stata-and-python
  • Post:Lawrence Devon
  • July 17, 2021
  • Read 109
  • 38
  • 17

Python To STATA Cheat Sheet

Python and STATA are popular programming languages. The biggest difference between the two is that Python allows you to do a wide range of things while Stata is known for data analysis. The great advantage to any programmer is knowing how to use python within Stata for optimum results. In Stata 16 you can execute Python code within Stata. Stata has a new python command that gives you several subcommands helping you to call Python from Stata. It also enables you to output Python results within Stata.


Below Is The Python To Stata Cheat Sheet That Will Come In Handy


  • Reading and saving files

    If you want to read.dta (stata) file

    Stata) - use file. dtaPython pd. read stata (“file.dta”

  • Using .dta file with specific columns

    Stata) – Use var1 var2 using file.dta

    Python- pd. read stata (“file.dta”), columns= [‘var1’, ‘var2’]

  • Reading .csv files or.xlsx files

    Stata)-Import Excel file using excel_file.xlsx

    Python- pd. read excel (‘excel_file.xlsx’) Stata) import using csvfile.csv

    Python) pd. read csv (“csvfile.csv”)

  • Saving .dta file to a given directory

    Stata) save file.dta, replacePython) df.to stata (“file.dta”)

    In the above sentence, the parameter “replace” in the STATA command means that you will replace the pre-existing file.dta file with the present version you are saving.


Description And Summary Statistics


  • Describe

    Stata) - describePython) df.info ( )

  • Total number of observations

    Stata) countPython) len (df) or df. shape [0]

    If you combine the count command with the If statement in Stata, you will get the number of observations that satisfy a given condition.

    Example: count if name last== “Wood” (It will count the number of observations whose last name is Wood).


Basic Data Wrangling and Operations


  • Sort observations using var or multiple vars

    Stata) sort var1 var2Python) df, sort values ( [‘var1’, ‘var2])

  • Keep or drop observations based on certain conditions

    Stata) Keep if< condition> drop if < condition>


You can start your Python journey within Stata if you know the common commands. Hope this cheat sheet comes in handy for you.

Recommended

We Assure You to Fetch Highest Grades & Provide 24/7 Live Customer Support
We Provide Discounts To Regular Customers